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

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

    I needed to get all files from my C: partition so i combined Marc and Jaider answers and got function with no recursion and with parallel programming with result of about 370k files processed in 30 seconds. Maybe this will help someone:

    void DirSearch(string path)
        {
            ConcurrentQueue pendingQueue = new ConcurrentQueue();
            pendingQueue.Enqueue(path);
    
            ConcurrentBag filesNames = new ConcurrentBag();
            while(pendingQueue.Count > 0)
            {
                try
                {
                    pendingQueue.TryDequeue(out path);
    
                    var files = Directory.GetFiles(path);
    
                    Parallel.ForEach(files, x => filesNames.Add(x));
    
                    var directories = Directory.GetDirectories(path);
    
                    Parallel.ForEach(directories, (x) => pendingQueue.Enqueue(x));
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }
    

提交回复
热议问题