Anuya Anuya - 2 months ago 23
C# Question

Move all files in subfolders to another folder using c#

My source path is

C:\Music\
in which I have hundreds of folders called Album-1, Album-2 etc.

What I want to do is create a folder called
Consolidated
in my source path.

And then I want to move all the files inside my albums to the folder
Consolidated
, so that I get all the music files in one folder.

How can I do this ?

Answer

Try like this

String directoryName = "C:\\Consolidated";
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if (dirInfo.Exists == false)
    Directory.CreateDirectory(directoryName);

List<String> MyMusicFiles = Directory
                   .GetFiles("C:\\Music", "*.*", SearchOption.AllDirectories).ToList();

foreach (string file in MyMusicFiles)
{
    FileInfo mFile = new FileInfo(file);
    // to remove name collisions
    if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false) 
    {
         mFile.MoveTo(dirInfo + "\\" + mFile.Name);
    }
}

It will get all the files in the "C:\Music" folder (including files in the subfolder) and move them to the destination folder. The SearchOption.AllDirectories will recursively search all the subfolders.