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

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

    Try Parallel programming:

    private string _fileSearchPattern;
    private List _files;
    private object lockThis = new object();
    
    public List GetFileList(string fileSearchPattern, string rootFolderPath)
    {
        _fileSearchPattern = fileSearchPattern;
        AddFileList(rootFolderPath);
        return _files;
    }
    
    private void AddFileList(string rootFolderPath)
    {
        var files = Directory.GetFiles(rootFolderPath, _fileSearchPattern);
        lock (lockThis)
        {
            _files.AddRange(files);
        }
    
        var directories = Directory.GetDirectories(rootFolderPath);
    
        Parallel.ForEach(directories, AddFileList); // same as Parallel.ForEach(directories, directory => AddFileList(directory));
    }
    

提交回复
热议问题