A list of all folders that match a specific path pattern

I need to perform some operations in all folders in a shared folder that match a specific template. A template can refer to a number of levels in a tree, for example. \Test\[az]+\Project[0-9]{3}

What is the most efficient way to traverse a tree to find all the matching folders? Is there a better way to do this than simply searching for recursive depth using DirectoryInfo and di.GetDirectories (), for example:

 private void TraverseSubFolder(DirectoryInfo folder) { if (filter.IsMatch(folder.FullName)) { DoStuff(folder); } DirectoryInfo[] subFolders = folder.GetDirectories(); foreach (DirectoryInfo sf in subFolders) { TraverseSubFolder(sf); } } 
+3
Oct 30 '09 at 19:35
source share
2 answers

You can use Linq to filter

 Regex regex = new Regex("your regex"); var directories = Directory.GetDirectories("c:\\", null, SearchOption.AllDirectories).Where(directory => regex.IsMatch(directory)); 

The disadvantage of this approach is that it will still search in an unwanted folder that has been filtered, since Where happens after all folders are returned.

It can be adapted.

Edit

This will not work with SearchOption.AllDirectories, because as soon as you get to a folder in which you do not have permission, a UnauthorizedAccessException will be thrown.

I do not think that you can go without a recursive function due to a UnauthorizedAccessException check.

I encoded this approach using Linq, but it is not much different from your own approach. At least he checks permission. It is still subject to a StackOverflowException.

 private static void Traverse(List<string> folders, string rootFolder, Regex filter) { try { // Test for UnauthorizedAccessException new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootFolder).Demand(); Array.ForEach(Directory.GetDirectories(rootFolder), (directory) => { if (filter.IsMatch(directory)) { folders.Add(directory); Traverse(folders, directory, filter); } }); } catch { // Ignore folder that we don't have access to } } // Usage example List<string> folders = new List<string>(); Regex regex = new Regex("^.+$"); Traverse(folders, "e:\\projects", regex); 
+4
30 Oct. '09 at 19:44
source share

Directory.GetDirectories (.., .., SearchOption.AllDirectories)

0
Oct. 30 '09 at 19:37
source share



All Articles