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.

Be First to Comment

Leave a Reply