C# Search base folder and subdirectories for a folder with a specific name

1.9k views Asked by At

I have a system tray application that makes use of ContextMenus to dynamically create a list of folders depending upon a SQL result set.

After the SQL result set is generated, this returns a list of active tasks. The application then generates ToolStripMenuItem for each of the active tasks from the result set using a for each loop.

This is where I begin to struggle. I have been searching for a while now for the best way to enable users to open these dynamically created folders.

I have created an on click event handler that is controlled by the sender, but I am unable to think of a decent (working) way to then find the file paths for the folders created.

I have a base folder, lets say "C:\" with two subfolders, 2014 and 2015. I need my application to take the folder name clicked on and search for the actual folder within "C:\" and sub folders of "C:\", then open this with process.start.

I began by creating a for each loop using System.IO.Directory.GetDirectories, however this only seems to find the first set of folders (EG: 2014, 2015), even when using the SearchOption.AllDirectories method overload. Code example:

string path2 = @"C:\";
foreach (string dir in System.IO.Directory.GetDirectories(path2, SearchOption.AllDirectories))
    {
        if (new DirectoryInfo(dir).Name.Contains(test))
        {
            MessageBox.Show(dir);
        }
    }

Can any one provide some ideas as to how to search for folders and sub folders that contain a pre-defined string (which wont necessarily complete the full folder path), so that the full file path can be returned?

Thanks

2

There are 2 answers

0
Aris Skam On

In order to get all sub folders you can use this code

DirectoryInfo dirInfo = new DirectoryInfo(@"Path to Folder");
DirectoryInfo[] subFolders = dirInfo.GetDirectories();

And then search for each subfolder if the name is 2014 or 2015 or whatever...

1
Jashaszun On

I'm honestly not even sure how your code compiles, because in my C# there is no overload of Directory.GetDirectories(...) that takes a string and a SearchOption.

It seems to me that you don't need recursion, but in fact only need to use a specific overload of Directory.GetDirectories:

string path2 = @"C:\";
foreach (string dir in Directory.GetDirectories(path2, test, SearchOption.AllDirectories))
{
    // do what you want with dir.
}

This says "for each directory and sub-directory in path2 whose name matches test, do ...".