Possible Duplicate:
Can you call Directory.GetFiles() with multiple filters?
Does it possible to get for ex. .c
and .h
files from directory. Usage of Directory.GetFile开发者_StackOverflow社区s("C:\", ".c;.h");
does not work. It's too bad to invoke Directory.GetFiles(...);
twice.. :(
Thanks.
If you're using .NET 4.0, I'd go with Directory.EnumerateFiles
:
var files = from f in Directory.EnumerateFiles("C:\\")
where f.EndsWith(".c") || f.EndsWith(".h")
select f;
its not possible to specify multiple filters in single GetFiles() method call. You can find alternatives here
you can try something like this:
var query = from p in Directory.GetFiles(@"C:\").AsEnumerable()
where p.Contains(".c")
|| p.Contains(".h")
select p;
For .Net 3.5.
public IEnumerable<string> GetFiles(
string basePath,
params string[] searchPatterns)
{
if (searchPatterns == null || searchPatterns.Length == 0)
{
return Directory.GetFiles(basePath);
}
return Enumerable.SelectMany(searchPatterns,
p => Directory.GetFiles(basePath, p));
}
Usage:
GetFiles(@"c:\", "*.c", "*.h");
you probably want to add some validation
See How to get files with multiple extensions using extension methods.
Here's some useful helper functions to simulate having multiple filters:
// .NET 4.0 friendly
public static IEnumerable<string> EnumerateFiles(string path, params string[] filters)
{
return filters.Length == 0
? Directory.EnumerateFiles(path)
: filters.SelectMany(filter => Directory.EnumerateFiles(path, filter));
}
// .NET 3.5 friendly
public static IEnumerable<string> GetFiles(string path, params string[] filters)
{
return filters.Length == 0
? Directory.GetFiles(path)
: filters.SelectMany(filter => Directory.GetFiles(path, filter));
}
精彩评论