80sRocker 80sRocker - 4 months ago 41
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

Please consider some implementation like this one:

public static class Program
{
    public static void Main()
    {
        var directoryPaths = new List<string>
            {
                @"C:\root\path_1",
                @"C:\root\path_2",
                @"C:\root\path_3"
                // …
            };
        var searchPatterns = new List<string>
            {
                "*.jpg",
                "*.gif"
            };

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

        // …
    }

    private static IEnumerable<string> EnumerateFiles(
        string path,
        IEnumerable<string> searchPatterns,
        SearchOption searchOption)
    {
        var filePaths = searchPatterns.SelectMany(
            searchPattern => Directory.EnumerateFiles(path, searchPattern, searchOption));
        return filePaths;
    }
}