0

I'm trying to use multiple filters with the Directory.GetFiles() command.

So say I want to match both .html and .css files. I'm using this:

Directory.GetFiles(path,"*.html|*.css");

I don't see any documentation however that this is supported, and it ends up not matching either HTML or CSS files. Is there something I'm missing?

Earlz
  • 62,085
  • 98
  • 303
  • 499

2 Answers2

3

The Directory.GetFiles function doesn't support multiple filters. My solution:

string patter = "*.jpg|*.png|*.gif";
string[] filters = patter.Split('|');
foreach(string filter in filters )
{
  // call Directory.GetFiles(path, filter) here;
}
Andrei Schneider
  • 3,618
  • 1
  • 33
  • 41
  • It's very unefficient. Call Directory.GetFiles(path) once, and filter results with LINQ or something alike – ppiotrowicz Jan 05 '11 at 11:21
  • 2
    @ppiotrowicz: How is that inefficient? If you use the LINQ approach you must retrieve the list of all files in the directory, and that can be a very long list. Using this approach you only retrieve the relevant entries. – Rune Grimstad Jan 05 '11 at 11:23
  • 1
    @rune it depends, if GetFiles is slow because of native Win32 calls it can easily be faster just to get a list of ALL files and filter it in-memory. It requires profiling though to see for sure what is faster. – Pauli Østerø Jan 05 '11 at 11:29
  • This runs from a T4 template, so it doesn't matter much as long as it isn't extremely slow. – Earlz Jan 05 '11 at 11:31
  • 1
    @rune It's inefficient because you still need to traverse all files (couple of times in your case) and you need to remove duplicates (of course not if you search by extension). – ppiotrowicz Jan 05 '11 at 11:40
  • I agree with Pauli that profiling is required to see which is faster. Most probably this will vary depending on the number of files in the folder and the filter applied. Do we know that GetFiles or whatever is calls doesn't cache the list of files? Just asking here :-) – Rune Grimstad Jan 05 '11 at 12:22
  • I needed to do this exact same thing, on a folder that returns just over 3000 files, the suggested method took 8 seconds, while filtering using linq took 2 seconds. – kay.one May 30 '11 at 03:39
1

There is also a descent solution which avoids foreach loops (with the help of Linq):

string[] filters = new[]{"*.jpg", "*.png", "*.gif"};
string[] filePaths = filters.SelectMany(f => Directory.GetFiles(basePath, f)).ToArray();
Bas1l
  • 271
  • 1
  • 4
  • 6