I am trying to use the Directory.GetFiles()
method to retrieve a list of files of multiple types, such as mp3
\'s and jpg
\'s. I have t
for
var exts = new[] { "mp3", "jpg" };
You could:
public IEnumerable FilterFiles(string path, params string[] exts) {
return
Directory
.EnumerateFiles(path, "*.*")
.Where(file => exts.Any(x => file.EndsWith(x, StringComparison.OrdinalIgnoreCase)));
}
Directory.EnumerateFiles
for a performance boost (What is the difference between Directory.EnumerateFiles vs Directory.GetFiles?).EndsWith("aspx", StringComparison.OrdinalIgnoreCase)
rather than .ToLower().EndsWith("aspx")
)But the real benefit of EnumerateFiles
shows up when you split up the filters and merge the results:
public IEnumerable FilterFiles(string path, params string[] exts) {
return
exts.Select(x => "*." + x) // turn into globs
.SelectMany(x =>
Directory.EnumerateFiles(path, x)
);
}
It gets a bit faster if you don't have to turn them into globs (i.e. exts = new[] {"*.mp3", "*.jpg"}
already).
Performance evaluation based on the following LinqPad test (note: Perf
just repeats the delegate 10000 times)
https://gist.github.com/zaus/7454021
( reposted and extended from 'duplicate' since that question specifically requested no LINQ: Multiple file-extensions searchPattern for System.IO.Directory.GetFiles )