tags:

views:

64

answers:

2

Hi

How to find all files matches a regex pattern in a folder?

Thanks

+7  A: 

The GetFiles method allows you to specify a wildcard pattern but not really a regex. Another possibility is to simply loop through the files and validate their name against a regex.

IEnumerable<string> files = Directory
    .EnumerateFiles(@"c:\somePath")
    .Where(name => Regex.IsMatch(name, "SOME REGEX"));
Darin Dimitrov
+1 Nice ... didn't know something like this even existed :)
Rashmi Pandit
The `Directory.EnumerateFiles` was a great addition to .NET 4.0 as it returns `IEnumerable<string>` instead of `string[]` meaning that unless you start enumerating it won't block.
Darin Dimitrov
btw, `Directory.EnumerateFiles` is a .NET 3.5 feature
abatishchev
@abatishchev, no it isn't, checkout the doc: http://msdn.microsoft.com/en-us/library/dd383458.aspx
Darin Dimitrov
Yeap, http://msdn.microsoft.com/en-us/library/dd383458%28VS.90%29.aspx :)
abatishchev
@abatishchev: Read that document more closely. Specifically the Version Information part which says "Supported in: 4".
Tergiver
@Tergiver, @Darin: Thanks!
abatishchev
A: 

Regex matching of filesystem is not supported you will have to iterate through each of the files in the directory and check them individually

Nissim