XSL XSL - 1 month ago 9
C# Question

Directory.GetFiles of certain extension

Is there a way to simplify this linq expression, or is there a better way of doing this?

Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(s => s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||

Basically I want to return all files of a certain extension. Unfortunately, this method isn't very flexible. I'd rather be able to add extensions to a list and have Directory.GetFiles return those extensions. Is that possible?


If you would like to do your filtering in LINQ, you can do it like this:

var ext = new List<string> {"jpg", "gif", "png"};
var myFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
     .Where(s => ext.Contains(Path.GetExtension(s));

Now ext contains a list of allowed extensions; you can add or remove items as necessary for flexible filtering.