Is there a faster way than this to find all the files in a directory and all sub directories?

前端 未结 16 1446
盖世英雄少女心
盖世英雄少女心 2020-11-29 17:49

I\'m writing a program that needs to search a directory and all its sub directories for files that have a certain extension. This is going to be used both on a local, and a

16条回答
  •  不知归路
    2020-11-29 17:57

    Cool question.

    I played around a little and by leveraging iterator blocks and LINQ I appear to have improved your revised implementation by about 40%

    I would be interested to have you test it out using your timing methods and on your network to see what the difference looks like.

    Here is the meat of it

    private static IEnumerable GetFileList(string searchPattern, string rootFolderPath)
    {
        var rootDir = new DirectoryInfo(rootFolderPath);
        var dirList = rootDir.GetDirectories("*", SearchOption.AllDirectories);
    
        return from directoriesWithFiles in ReturnFiles(dirList, searchPattern).SelectMany(files => files)
               select directoriesWithFiles;
    }
    
    private static IEnumerable ReturnFiles(DirectoryInfo[] dirList, string fileSearchPattern)
    {
        foreach (DirectoryInfo dir in dirList)
        {
            yield return dir.GetFiles(fileSearchPattern, SearchOption.TopDirectoryOnly);
        }
    }
    

提交回复
热议问题