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 {
Pierre-Alain Vigeant 30 Oct. '09 at 19:44 2009-10-30 19:44
source share