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 tried both of the following with no luck:
Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories);
Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories);
Is there a way to do this in one call?
If you are using VB.NET (or imported the dependency into your C# project), there actually exists a convenience method that allows to filter for multiple extensions:
In VB.NET this can be accessed through the My-namespace:
Unfortunately, these convenience methods don't support a lazily evaluated variant like
Directory.EnumerateFiles()
does.If you have a large list of extensions to check you can use the following. I didn't want to create a lot of OR statements so i modified what lette wrote.
Another way to use Linq, but without having to return everything and filter on that in memory.
It's actually 2 calls to
GetFiles()
, but I think it's consistent with the spirit of the question and returns them in one enumerable.I know it's old question but LINQ: (.NET40+)
hope this helps someone: