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

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

    In .NET 4.5, at least, there's this version that is much shorter and has the added bonus of evaluating any file criteria for inclusion in the list:

    public static IEnumerable<string> GetAllFiles(string path, 
                                                  Func<FileInfo, bool> checkFile = null)
    {
        string mask = Path.GetFileName(path);
        if (string.IsNullOrEmpty(mask)) mask = "*.*";
        path = Path.GetDirectoryName(path);
        string[] files = Directory.GetFiles(path, mask, SearchOption.AllDirectories);
    
        foreach (string file in files)
        {
            if (checkFile == null || checkFile(new FileInfo(file)))
                yield return file;
        }
    }
    

    Use like this:

    var list = GetAllFiles(mask, (info) => Path.GetExtension(info.Name) == ".html").ToList();
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 00:52
    static void Main(string[] args)
            {
                string[] array1 = Directory.GetFiles(@"D:\");
                string[] array2 = System.IO.Directory.GetDirectories(@"D:\");
                Console.WriteLine("--- Files: ---");
                foreach (string name in array1)
                {
                    Console.WriteLine(name);
                }
                foreach (string name in array2)
                {
                    Console.WriteLine(name);
                }
                      Console.ReadLine();
            }
    
    0 讨论(0)
  • 2020-11-22 00:53
    Directory.GetFiles("C:\\", "*.*", SearchOption.AllDirectories)
    
    0 讨论(0)
  • 2020-11-22 00:54

    Shortest record

    string files = Directory.GetFiles(@"your_path", "*.jpg", SearchOption.AllDirectories);
    
    0 讨论(0)
  • 2020-11-22 00:56

    Some excellent answers but these answers did not solve my issue.

    As soon as a folder permission issue arises: "Permission Denied" the code fails. This is what I used to get around the "Permission Denied" issue:

    private int counter = 0;
    
        private string[] MyDirectories = Directory.GetDirectories("C:\\");
    
        private void ScanButton_Click(object sender, EventArgs e)
        {
            Thread MonitorSpeech = new Thread(() => ScanFiles());
            MonitorSpeech.Start();
        }
    
        private void ScanFiles()
        {
            string CurrentDirectory = string.Empty;
    
            while (counter < MyDirectories.Length)
            {
                try
                {
                    GetDirectories();
                    CurrentDirectory = MyDirectories[counter++];
                }
                catch
                {
                    if (!this.IsDisposed)
                    {
                        listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + CurrentDirectory); });
                    }
                }
            }
        }
    
        private void GetDirectories()
        {
            foreach (string directory in MyDirectories)
            {
                GetFiles(directory);
            }
        }
    
        private void GetFiles(string directory)
        {
            try
            {
                foreach (string file in Directory.GetFiles(directory, "*"))
                {
                    listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(file); });
                }
            }
            catch
            {
                listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + directory); });
            }
        }
    

    Hope this helps others.

    0 讨论(0)
提交回复
热议问题