Filter subdirectories when it's not equal to something.

Hi, I'm trying to search for directories that don't match a certain criteria. I want to get just the subdirectories not starting with 'F'.


This is what I'm doing at the moment but it's not working.

                var pattern = new Regex("^[^F].*");
                var dirs = from d in Directory.EnumerateDirectories(Path, "*", SearchOption.TopDirectoryOnly)
                           where pattern.IsMatch(d)
                           select d;

Open in new window

This code returns all the subdirectories ignoring the filter expression.
I think it's looking at the root directory instead of looking in the subdirectories of \root. So because the root starts with 'D\' it thinks it's all good. If I change the regular expression to the one below, I get nothing.

   var pattern = new Regex("^[^D].*");

Open in new window

Adrian CrossAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
You can use the LINQ Where clause, along with the Name property of a DirectoryInfo instance. Something like this:

var pattern = new Regex("^[^F].*");
var dirs = Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
var result = dirs.Where(d => pattern.IsMatch(new DirectoryInfo(d).Name)).ToList();

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Terry WoodsIT GuruCommented:
Would this work?:
 var pattern = new Regex("^D:\\root\\[^F].*");

Open in new window

Note that sometimes backslashes need to be double escaped; not sure if this is one of those times!
 var pattern = new Regex("^D:\\\\root\\\\[^F].*");

Open in new window

Adrian CrossAuthor Commented:
Thanks both for your help
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.