2009
10.13

Another thing it can be handy to do is get a List<> of all files in a directory and contained subdirectories. This is nice if you are doing something like programmatically registering a bunch of legacy COM components. Again, what I want is something like this:

File.GetFilesRecursively(string dir, List result);
Since I couldn’t find this in the .NET framework I wrote a recursive one:

private static void GetFilesRecursively(string dir, List result)
{
    string[] files = Directory.GetFiles(dir);

    foreach (string file in files)
    {
        result.Add(file);
    }

    foreach (string directory in Directory.GetDirectories(dir))
    {
        GetFilesRecursively(directory, result);
    }                        
}

Just pass in the directory name and a List that you have just new’ed and it will give you a recursive list of all files in that directory.

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!