erenjs
erenjs

Reputation: 75

How to move files WHILE creating their folders. Directory.Method, etc

I've found a python post on this but couldn't "convert" it...

So I already have this:

    if (Directory.GetFiles(sourcePath, "*_Items_*.pdf").Any())
    {
        string[] pdfFiles = Directory.GetFiles(sourcePath, "*_Items_*.pdf");
        foreach (string path in pdfFiles)
        {
            file = Path.GetFileName(path);
            subString = file.Substring(0, 8);
            Directory.CreateDirectory(Path.Combine(targetPath, subString));
        } 
    }

So in the code I take letters out of files and create folders with those substrings. How would I also move these files directly to their folder created with their substring?

If else because I make a message that says "No items list found" when there are no files.

Every help appreciated, thanks.

Upvotes: 1

Views: 49

Answers (2)

Antoine V
Antoine V

Reputation: 7204

There are 2 methods FileInfo.MoveTo() vs File.Move() to use.

The code can be like with the help of LINQ : Create a directory for each file after a check if the folder exists already. Then move to the new folder created

var files = Directory.GetFiles(sourcePath, "*_Items_*.pdf").ToList();

files.ForEach(f => {
    var fileInfo = new FileInfo(f);
    var pathName= fileInfo.Name.Substring(0, 8);

    var directoryInfo = new DirectoryInfo(Path.Combine(targetPath, pathName));
    if(!directoryInfo.Exists)
       directoryInfo.Create();

    fileInfo.MoveTo(Path.Combine(directoryInfo.FullName, fileInfo.Name); // think about if file already exist

})

Upvotes: 2

ProgrammingLlama
ProgrammingLlama

Reputation: 38777

I'd imagine you can simply use File.Move to move the file.

foreach (string path in pdfFiles)
{
    file = Path.GetFileName(path);
    subString = file.Substring(0, 8);
    var targetFolder = Path.Combine(targetPath, subString);
    Directory.CreateDirectory(targetFolder);
    // Move the file into the created folder
    File.Move(path, Path.Combine(targetFolder, file));
} 

Upvotes: 2

Related Questions