-->

Multiple filters with Directory.GetFiles?

2019-09-11 12:21发布

问题:

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?

回答1:

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;
}


回答2:

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();