How to recursively list all the files in a directory in C#?

前端 未结 22 2980
长发绾君心
长发绾君心 2020-11-22 00:07

How to recursively list all the files in a directory and child directories in C#?

22条回答
  •  渐次进展
    2020-11-22 00:45

    Note that in .NET 4.0 there are (supposedly) iterator-based (rather than array-based) file functions built in:

    foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
    {
        Console.WriteLine(file);
    }
    

    At the moment I'd use something like below; the inbuilt recursive method breaks too easily if you don't have access to a single sub-dir...; the Queue usage avoids too much call-stack recursion, and the iterator block avoids us having a huge array.

    static void Main() {
        foreach (string file in GetFiles(SOME_PATH)) {
            Console.WriteLine(file);
        }
    }
    
    static IEnumerable GetFiles(string path) {
        Queue queue = new Queue();
        queue.Enqueue(path);
        while (queue.Count > 0) {
            path = queue.Dequeue();
            try {
                foreach (string subDir in Directory.GetDirectories(path)) {
                    queue.Enqueue(subDir);
                }
            }
            catch(Exception ex) {
                Console.Error.WriteLine(ex);
            }
            string[] files = null;
            try {
                files = Directory.GetFiles(path);
            }
            catch (Exception ex) {
                Console.Error.WriteLine(ex);
            }
            if (files != null) {
                for(int i = 0 ; i < files.Length ; i++) {
                    yield return files[i];
                }
            }
        }
    }
    

提交回复
热议问题