GetFiles with multiple extensions

rd42 picture rd42 · Aug 20, 2010 · Viewed 131.3k times · Source

Possible Duplicate:
Can you call Directory.GetFiles() with multiple filters?

How do you filter on more than one extension?

I've tried:

FileInfo[] Files = dinfo.GetFiles("*.jpg;*.tiff;*.bmp");
FileInfo[] Files = dinfo.GetFiles("*.jpg,*.tiff,*.bmp");

Answer

SLaks picture SLaks · Nov 8, 2010

You can get every file, then filter the array:

public static IEnumerable<FileInfo> GetFilesByExtensions(this DirectoryInfo dirInfo, params string[] extensions)
{
    var allowedExtensions = new HashSet<string>(extensions, StringComparer.OrdinalIgnoreCase);

    return dirInfo.EnumerateFiles()
                  .Where(f => allowedExtensions.Contains(f.Extension));
}

This will be (marginally) faster than every other answer here.
In .Net 3.5, replace EnumerateFiles with GetFiles (which is slower).

And use it like this:

var files = new DirectoryInfo(...).GetFilesByExtensions(".jpg", ".mov", ".gif", ".mp4");