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

前端 未结 22 2546
长发绾君心
长发绾君心 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:51

    Some improved version with max lvl to go down in directory and option to exclude folders:

    using System;
    using System.IO;
    
    class MainClass {
      public static void Main (string[] args) {
    
        var dir = @"C:\directory\to\print";
        PrintDirectoryTree(dir, 2, new string[] {"folder3"});
      }
    
    
      public static void PrintDirectoryTree(string directory, int lvl, string[] excludedFolders = null, string lvlSeperator = "")
      {
        excludedFolders = excludedFolders ?? new string[0];
    
        foreach (string f in Directory.GetFiles(directory))
        {
            Console.WriteLine(lvlSeperator+Path.GetFileName(f));
        } 
    
        foreach (string d in Directory.GetDirectories(directory))
        {
            Console.WriteLine(lvlSeperator + "-" + Path.GetFileName(d));
    
            if(lvl > 0 && Array.IndexOf(excludedFolders, Path.GetFileName(d)) < 0)
            {
              PrintDirectoryTree(d, lvl-1, excludedFolders, lvlSeperator+"  ");
            }
        }
      }
    }
    

    input directory:

    -folder1
      file1.txt
      -folder2
        file2.txt
        -folder5
          file6.txt
      -folder3
        file3.txt
      -folder4
        file4.txt
        file5.txt
    

    output of the function (content of folder5 is excluded due to lvl limit and content of folder3 is excluded because it is in excludedFolders array):

    -folder1
      file1.txt
      -folder2
        file2.txt
        -folder5
      -folder3
      -folder4
        file4.txt
        file5.txt
    

提交回复
热议问题