Recursively Getting Directory Contents in C#

Have you ever wanted an easy way to get all of the contents of a directory into one array, regardless of how many levels of subfolders there are? This is a task for my favourite kind of programming – nested loops!

The following function will do the job nicely:

private static void listDirectoryNest(string path, ref List<string> currentList, bool includedirs)
{

    foreach (string dir in Directory.GetDirectories(path))
    {
        listDirectoryNest(dir + "\\", ref currentList, includedirs);
        if (includedirs)
            currentList.Add(dir + "\\");
    }

    foreach (string file in Directory.GetFiles(path))
    {
        currentList.Add(file);
    }

}

This function takes the string path which defines where the nesting is to start, for example e:\documents. It then takes the reference currentList which is a generic string list. After the function is run this string list will contain all of the files within the original path (including those in subfolders). The final variable, includedirs defines whether or not to include directories in the currentList output. If you set this variable to true then you can determine which entries in currentList are directories by checking if they end with the \ character.

This is an example of how to call the function above:

List<string> output = new List<string>();

listDirectoryNest("e:\\documents", ref output, true);

After running that code, output will contain all of the contents of e:\documents\, including subfolders, in a format like:

  • e:\documents\something.doc
  • e:\documents\something-else.xls
  • e:\documents\some subfolder\
  • e:\documents\some subfolder\subdocument.xls
  • e:\documents\my pictures\
  • e:\documents\my pictures\photo.jpg

Leave a comment

Your comment