Search code examples
c#create-directory

Trying to move files from one folder to another with subfolders C#


I want to reorganize all the photos from one folder into subfolders of another path, where I want to create new subfolders named with the file creation dates.

Example:

photo1.png (creation date 12.02.2015)

photo2.png (creation date 12.02.2015)

photo3.png (creation date 13.02.2015)

--> create two subfolders: "12-feb-2015" with photo1.png and photo2.png and "13-feb-2015" with photo3.png

I wrote the code for copying the photos into the other folder and create subfolder with the current date. But I don't know how to create the subfolders named after the creation date of the files.

public class SimpleFileCopy
{
    static void Main(string[] args)
    {
        // Specify what is done when a file is changed, created, or deleted.
        string fileName = "*.png";
        string sourcePath = @"C:\tmp";
        string targetPath = @"U:\\";
        
        // Use Path class to manipulate file and directory paths.
        string sourceFile = Path.Combine(sourcePath, fileName);
        //string destFile = Path.Combine(Directory.CreateDirectory("U:\\" + DateTime.Now.ToString("dd-MMM-yyyy") , fileName);

        // To copy a folder's contents to a new location:
        // Create a new target folder, if necessary.
        if (!Directory.Exists("U:\\" + Directory.CreateDirectory("U:\\" + DateTime.Now.ToString("dd-MMM-yyyy"))))

        {
            Directory.CreateDirectory("U:\\" + Directory.CreateDirectory("U:\\" + DateTime.Now.ToString("dd-MMM-yyyy")));
        }
        else
        // To copy a file to another location and 
        // overwrite the destination file if it already exists.
        {

            foreach (var file in new DirectoryInfo(sourcePath).GetFiles(fileName))
            {
                try
                {
                    file.CopyTo(e.FullPath.Combine(targetPath + Directory.CreateDirectory("U:\\" + DateTime.Now.ToString("dd-MMM-yyyy")), file.Name));
                }
                catch { }
            }
        }
    }
}

Solution

  • You are having way to many Directory.CreateDirectory calls. Just enumerate your source folder files, then get the date with file.CreationTime, call Directory.CreateDirectory (no matter if it already exists) and then copy your file.

    string fileName = "*.png";
    string sourcePath = @"C:\tmp";
    string targetPath = @"U:\";
    
    foreach (var file in new DirectoryInfo(sourcePath).GetFiles(fileName))
    {
        var targetFolderName = file.CreationTime.ToString("dd-MMM-yyyy");
        var dir = Directory.CreateDirectory(Path.Combine(targetPath, targetFolderName));
        file.CopyTo(Path.Combine(dir.FullName, file.Name), true);
    }