最快和最简单的方式输出文件夹递归作为树

本文关键字:递归 文件夹 输出 方式 最简单 | 更新日期: 2023-09-27 18:09:46

是否有更好(更快)的方法来做同样的事情?如果有很多文件夹。
我对算法了解不多,我希望有人能给我一个更好的算法。

我使用如下代码完成工作:

        private static void ShowAllFoldersUnder(string path, int indent)
        {
            try
            {
                if ((File.GetAttributes(path) & FileAttributes.ReparsePoint)
                    != FileAttributes.ReparsePoint)
                {
                    foreach (string folder in Directory.GetDirectories(path))
                    {
                        Console.WriteLine(
                            "{0}{1}", new string(' ', indent), Path.GetFileName(folder));
                        ShowAllFoldersUnder(folder, indent + 2);
                    }
                }
            }
            catch (UnauthorizedAccessException ex) {
                Console.WriteLine(ex.Message); 
            }    
        }

输出样本结果

CompositeUI
  BuilderStrategies
  Collections
  Commands
  Configuration
    Xsd
  EventBroker
  Instrumentation
  obj
    Debug
      TempPE
  Properties
  Services
  SmartParts
  UIElements
  Utility
  Visualizer

最快和最简单的方式输出文件夹递归作为树

EnumerateDirectories可以更快,因为它不需要像GetDirectories那样分配一个文件夹名称数组。