2009
10.13

Copy Directory Recursively

There are a few things in C# that are not as easy to do as they should be. For instance, copying a directory along with all of its subfolders and contained files. What I want is a function that looks like this:

Directory.Copy(string sourceDir, string destDir)
I couldn’t find such a function in the .NET framework so I wrote a recursive one myself:

using System.IO;
private static void CopyDirectory(string srcDir, string destDir)
{
    if (destDir[destDir.Length - 1] != Path.DirectorySeparatorChar)
        destDir += Path.DirectorySeparatorChar;

    if (!Directory.Exists(destDir))
        Directory.CreateDirectory(destDir);

    string[] entries = Directory.GetFileSystemEntries(srcDir);
    foreach (string entry in entries)
    {
        //Recursive CopyDirectory call here
        if (Directory.Exists(entry))
            CopyDirectory(entry, destDir + Path.GetFileName(entry));  
        else
            File.Copy(entry, destDir + Path.GetFileName(entry), true); 
    }
}

You just need to make sure the directories are not already contained within each other in some way or it could be copying files until your drive fills up!

Comments are closed.