80sRocker 80sRocker - 1 year ago 280
C# Question

Directory.EnumerateFiles method: How to enumerate files in specified subdirectories?

Assume the following directory structure. "C:\Genre" and the "Genre" directory having several subdirectories: "Rock", "Pop", "Metal", "Jazz".

How would I tweak the following statement to search in "Rock" and "Metal" subdirectories only?

var myFiles = Directory.
EnumerateFiles("C:\Genre", "*", SearchOption.AllDirectories).
Where(s => s.EndsWith(".jpg") || s.EndsWith(".gif"));

Answer Source

Please consider some implementation like this one:

public static class Program
    public static void Main()
        var directoryPaths = new List<string>
                // …
        var searchPatterns = new List<string>

        var filePaths = directoryPaths
            .SelectMany(directoryPath =>
                EnumerateFiles(directoryPath, searchPatterns, SearchOption.AllDirectories))

        // …

    private static IEnumerable<string> EnumerateFiles(
        string path,
        IEnumerable<string> searchPatterns,
        SearchOption searchOption)
        var filePaths = searchPatterns.SelectMany(
            searchPattern => Directory.EnumerateFiles(path, searchPattern, searchOption));
        return filePaths;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download