Move all files in subfolders to another folder using c#

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.


You can use the Directory object to do this, but you might run into problems if you have the same file name in multiple sub directories (e.g. album1\1.mp3, album2\1.mp3) so you might need a little extra logic to tack something unique onto the names (e.g. album1-1.mp4).

    public void CopyDir( string sourceFolder, string destFolder )
    {
        if (!Directory.Exists( destFolder ))
            Directory.CreateDirectory( destFolder );

        // Get Files & Copy
        string[] files = Directory.GetFiles( sourceFolder );
        foreach (string file in files)
        {
            string name = Path.GetFileName( file );

            // ADD Unique File Name Check to Below!!!!
            string dest = Path.Combine( destFolder, name );
            File.Copy( file, dest );
        }

        // Get dirs recursively and copy files
        string[] folders = Directory.GetDirectories( sourceFolder );
        foreach (string folder in folders)
        {
            string name = Path.GetFileName( folder );
            string dest = Path.Combine( destFolder, name );
            CopyDir( folder, dest );
        }
    }

Basically, that can be done with Directory.Move:

                try
                {
                    Directory.Move(source, destination);
                }
                catch { }

don't see any reason, why you shouldn't use this function. It's recursive and speed optimized

Tags:

C#

Directory