Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #177 Find files for a list of filename extensions

Construct a list L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory D and all its subdirectories.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string D = @"C:\The\Search\Path";

// Assumes that the file system is case insensitive
HashSet<string> exts = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase) { "jpg", "jpeg", "png" };
IEnumerable<string> L =
Directory
    .EnumerateFiles(D, "*", SearchOption.AllDirectories)
    .Where(currentFile => exts.Contains(Path.GetExtension(currentFile)));

Enumerating all files under the given directory select any file whose extension exists in the HashSet (case insensitive using the current culture). If you want this to be case sensitive you can remove the comparer.

New implementation...
< >
Bart