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

前端 未结 16 1447
盖世英雄少女心
盖世英雄少女心 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 18:08

    Consider splitting the updated method into two iterators:

    private static IEnumerable GetDirs(string rootFolderPath)
    {
         DirectoryInfo rootDir = new DirectoryInfo(rootFolderPath);
         yield return rootDir;
    
         foreach(DirectoryInfo di in rootDir.GetDirectories("*", SearchOption.AllDirectories));
         {
              yield return di;
         }
         yield break;
    }
    
    public static IEnumerable GetFileList(string fileSearchPattern, string rootFolderPath)
    {
         var allDirs = GetDirs(rootFolderPath);
         foreach(DirectoryInfo di in allDirs())
         {
              var files = di.GetFiles(fileSearchPattern, SearchOption.TopDirectoryOnly);
              foreach(FileInfo fi in files)
              {
                   yield return fi;
              }
         }
         yield break;
    }
    

    Also, further to the network-specific scenario, if you were able to install a small service on that server that you could call into from a client machine, you'd get much closer to your "local folder" results, because the search could execute on the server and just return the results to you. This would be your biggest speed boost in the network folder scenario, but may not be available in your situation. I've been using a file synchronization program that includes this option -- once I installed the service on my server the program became WAY faster at identifying the files that were new, deleted, and out-of-sync.

提交回复
热议问题