Tip of the day #22: Obtaining all subdirectories recursively

This is an example of how to obtain a list of all subdirectories using a recursive method with the .NET Framework.

public static List<DirectoryInfo> GetSubdirectories(DirectoryInfo directory)
    // Set up the result of the method.List<DirectoryInfo>
    result = new List<DirectoryInfo>();

    // Attempt to get a list of immediate child directories from the directory
    // that was passed in to the method.
    DirectoryInfo[] childDirectories;
        childDirectories = directory.GetDirectories();
    catch (UnauthorizedAccessException uae)
        // If the permissions do not authorise access to the contents of the
        // directory then return an empty list.
        return result;

    // Loop over all the child directories to get their contents.
    foreach (DirectoryInfo childDirectory in childDirectories)
        // Add the child directory to the result list
        // Get any children of the current child directory
        List<DirectoryInfo> grandchildDirectories = GetSubdirectories(childDirectory);
        // Add the child's children (the grandchildren) to the result list.

    // return the full list of all subdirectories of the one passed in.
    return result;

The code requires the following namespaces:

  • System.Collections.Generic

  • System.IO

  • System.Diagnostics

Published by Colin Mackay

I blog at ColinMackay.scot. I also talk at software development conferences.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: