Link to home
Start Free TrialLog in
Avatar of Adrian Cross
Adrian Cross

asked on

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'.

D:\root\D1234
D:\root\D9876
D:\root\F1234
D:\root\F9876
D:\root\A1234

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

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

Avatar of Adrian Cross
Adrian Cross

ASKER

Thanks both for your help