C# Search for subdirectory (not for files)

Well

Directory.GetDirectories(root);

will return you an array of the subdirectories.

You can then use Linq to find the one you're interested in:

IEnumerable<string> list = Directory.GetDirectories(root).Where(s => s.Equals("test"));

which isn't a loop in your code, but is still a loop nevertheless. So the ultimate answer is that "no you can't find a folder 'test' without looping".

You could add .SingleOrDefault() to the Linq, but that would depend on what you wanted to do if your "test" folder couldn't be found.

If you change the GetDirectories call to include the SearchOption SearchOption.AllDirectories then it will do the recursion for you as well. This version supports searching - you have to supply a search string - though in .NET Framework it's case sensitive searching. To return all sub directories you pass "*" as the search term.

Obviously in this case the call could return more than one item if there was more than one folder named "test" in your directory tree.


var foldersFound = Directory.GetDirectories(root, "test", SearchOption.AllDirectories)

This will return a string array with all the folders found with the given name. You can change the last parameter so that it only checks top level directories and you can change root to adjust where it is starting from.