Find all Subdirectories from a given path using C#

To load the subdirectories for a given file path. We simply need to use the GetDirectories method of DirectoryInfo (this example loads the results into a listbox lstDirs)

E.g.

using System.IO;

private void loadSubDirs(string sPath)
{
    DirectoryInfo dInfo = new DirectoryInfo(sPath);
    DirectoryInfo[] subDirs = dInfo.GetDirectories();

    foreach (DirectoryInfo dir in subDirs)
    {
        lstDirs.Items.Add(dir.FullName);
    }
}

N.B. sPath needs to be a full path including drive letter “C:\files\morefiles\”

This will return all the subdirectories of the sPath Path. But only the first level…

If we want to get all the subdirectories, and their sub directories, etc.

We get loadSubDirs to call itself, passing each subdirectory to itself (recursion):

using System.IO;

private void loadSubDirs(string sPath)
{
    DirectoryInfo dInfo = new DirectoryInfo(sPath);
    DirectoryInfo[] subDirs = dInfo.GetDirectories();

    foreach (DirectoryInfo dir in subDirs)
    {
        lstDirs.Items.Add(dir.FullName);
        //call loadSubDirs with current dir name
        loadSubDirs(dir.FullName);
    }
}

This will give us all the directories and subdirectories beneath the passed sPath.

Advertisements
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Leave a Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s