Anuya Anuya - 1 year ago 131
C# Question

Move all files in subfolders to another folder using c#

My source path is

in which I have hundreds of folders called Album-1, Album-2 etc.

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

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

How can I do this ?

Answer Source

Try like this

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download