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.

  1. jordan 11

    Thanks again for the blog. Keep writing.