I'm going to jump the gun and assume you firstly want to get a single list of all directories beneath a given path (recursively). This code should do that:
string[] allDirs = Directory.GetDirectories(@"D:\", "*.*", SearchOption.AllDirectories);
or if you need all files based on a pattern, just go with:
string[] allFiles = Directory.GetFiles(@"D:\", "*.*", SearchOption.AllDirectories);
EDIT:
If you have trouble with UnauthorizedAccessException
, you can roll your own implementation using LINQ and recursion, such as:
private static IEnumerable<string> MyGetDirectories(string basePath)
{
try
{
string[] dirs = Directory.GetDirectories(basePath);
return dirs.Union(dirs.SelectMany(dir => MyGetDirectories(dir)));
}
catch(UnauthorizedAccessException)
{
return Enumerable.Empty<string>();
}
}
Which you can call (and turn back to an array) with something like:
string[] allDirs = MyGetDirectories(@"D:\").ToArray();
Supporting Multiple Base Paths
If you have an array with multiple base paths, we can use SelectMany
again to get everything in one list, so:
string[] basePaths = new string[] { @"C:\", @"D:\" };
string[] allDirs = basePaths.SelectMany(dir => MyGetDirectories(dir)).ToArray();
The meaning of this is that for each item in basePaths
, we will use that entry to select many matching items (in this case by calling MyGetDirectories
) and then everything is joined together into one big list. In the last step this is converted back into an array.