80sRocker 80sRocker - 2 months ago 17
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"));


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;