This is something which
should be simple - just pass
SearchOption.AllDirectories
to
the EnumerateDirectories
method[
^].
Unfortunately, it's not that simple. When your code encounters a directory to which it doesn't have access, the
EnumerateDirectories
method will throw an
UnauthorizedAccessException
and quit. There's no way to skip that directory and continue with the next one.
As a result, you'll need to write your own method to enumerate the directories. Something like this should work:
public static IEnumerable<DirectoryInfo> SafeEnumerateDirectories(DirectoryInfo root)
{
if (root == null) throw new ArgumentNullException("root");
if (!root.Exists) return Enumerable.Empty<DirectoryInfo>();
return SafeEnumerateDirectoriesCore(root);
}
private static IEnumerable<DirectoryInfo> SafeEnumerateDirectoriesCore(DirectoryInfo root)
{
var searchPaths = new Stack<DirectoryInfo>();
searchPaths.Push(root);
while (searchPaths.Count != 0)
{
DirectoryInfo currentPath = searchPaths.Pop();
yield return currentPath;
DirectoryInfo[] subFolders = null;
try
{
foreach (var subDirectory in currentPath.EnumerateDirectories())
{
searchPaths.Push(subDirectory);
}
}
catch (UnauthorizedAccessException)
{
}
}
}
You can then use LINQ to find the matching directories and open them:
string toFind = txtbox_find.Text;
var root = new DirectoryInfo(@"C:\");
var matchingDirectories = SafeEnumerateDirectories(root)
.Where(d => string.Equals(d.Name, toFind, StringComparison.OrdinalIgnoreCase))
;
foreach (DirectoryInfo directory in matchingDirectories)
{
Process.Start(new ProcessStartInfo
{
FileName = directory.FullName,
UseShellExecute = true,
Verb = "open"
});
}