【问题标题】:Method to get all files within folder and subfolders that will return a list获取将返回列表的文件夹和子文件夹中的所有文件的方法
【发布时间】:2012-12-27 15:41:11
【问题描述】:

我有一个方法可以遍历文件夹及其所有子文件夹并获取文件路径列表。但是,我只能弄清楚如何创建它并将文件添加到公共列表,但不知道如何返回列表。方法如下:

public List<String> files = new List<String>();

private void DirSearch(string sDir)
    {
        try
        {
            foreach (string f in Directory.GetFiles(sDir))
            {
                files.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                DirSearch(d);
            }
        }
        catch (System.Exception excpt)
        {
            MessageBox.Show(excpt.Message);
        }
    }

所以,我只是在代码中的某个位置调用DirSearch(),它用路径“填充”列表,但我希望能够多次使用它来创建具有不同目录的不同列表等。

【问题讨论】:

  • 为什么不在'DirSearch'中定义List'files'变量并让'DirSearch'返回'files'?
  • 谢谢,效果很好。这就是 C# 与其他语言(如 Java)的不同之处,它列出了所有文件或 nodejs 的 readdir。 C# 对文件和目录有不同的方法。谢谢:-)

标签: c# file methods recursion directory


【解决方案1】:

我不确定您为什么要将字符串添加到files,它被声明为字段而不是临时变量。您可以将DirSearch 的签名更改为:

private List<string> DirSearch(string sDir)

并且,在catch 块之后,添加:

return files;

或者,您可以在方法内创建一个临时变量并返回它,在我看来,这似乎是您可能想要的方法。否则,每次调用该方法时,新找到的字符串都会被添加到与之前相同的列表中,并且会出现重复。

【讨论】:

    【解决方案2】:

    您可以使用Directory.GetFiles 替换您的方法。

     Directory.GetFiles(dirPath, "*", SearchOption.AllDirectories)
    

    【讨论】:

    • 如果在任何时候,由于文件/文件夹权限而引发异常,则整个语句将不起作用。正确的? (这就是我最初编写辅助方法的原因)
    • 没错,但是您在具有相同问题的辅助方法中使用Directory.GetFilesDirectory.GetDirectory。从某种意义上说,辅助方法更好,它会产生更多的条目,但它也有可能会吞下一些(具有访问权限的)。更好的方法是使用Directory.EnumerateDirectoriesDirectory.EnumerateFiles,这将使您可以顺序访问迭代器,然后您可以检查每个文件/文件夹的权限。
    【解决方案3】:
    private List<String> DirSearch(string sDir)
    {
        List<String> files = new List<String>();
        try
        {
            foreach (string f in Directory.GetFiles(sDir))
            {
                files.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                files.AddRange(DirSearch(d));
            }
        }
        catch (System.Exception excpt)
        {
            MessageBox.Show(excpt.Message);
        }
    
        return files;
    }
    

    如果您不想将整个列表加载到内存中并避免阻塞,您可以查看following answer

    【讨论】:

      【解决方案4】:

      只需使用这个:

      public static List<String> GetAllFiles(String directory)
      {
          return Directory.GetFiles(directory, "*.*", SearchOption.AllDirectories).ToList();
      }
      

      如果你想要每个文件,甚至是无扩展名的文件:

      public static List<String> GetAllFiles(String directory)
      {
          return Directory.GetFiles(directory, "*", SearchOption.AllDirectories).ToList();
      }
      

      【讨论】:

        【解决方案5】:

        你可以使用这样的东西:

        string [] filePaths = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
        

        除了使用“.”之外,您还可以输入文件名或仅输入“*.txt”之类的类型 SearchOption.AllDirectories 也是在所有子文件夹中搜索,如果您只想要一个级别,您可以更改它 更多关于如何在here上使用它

        【讨论】:

          【解决方案6】:

          试试这个
          课堂节目 { 静态无效主要(字符串 [] 参数) {

                  getfiles get = new getfiles();
                  List<string> files =  get.GetAllFiles(@"D:\Rishi");
          
                  foreach(string f in files)
                  {
                      Console.WriteLine(f);
                  }
          
          
                  Console.Read();
              }
          
          
          }
          
          class getfiles
          {
              public List<string> GetAllFiles(string sDirt)
              {
                  List<string> files = new List<string>();
          
                  try
                  {
                      foreach (string file in Directory.GetFiles(sDirt))
                      {
                          files.Add(file);
                      }
                      foreach (string fl in Directory.GetDirectories(sDirt))
                      {
                          files.AddRange(GetAllFiles(fl));
                      }
                  }
                  catch (Exception ex)
                  {
          
                      Console.WriteLine(ex.Message);
                  }
          
          
          
                  return files;
              }
          }
          

          【讨论】:

            【解决方案7】:
            String[] allfiles = System.IO.Directory.GetFiles("path/to/dir", "*.*", System.IO.SearchOption.AllDirectories);
            

            【讨论】:

            • 这和山姆的answer有什么不同?
            • 这是您发布的 CSharp 代码,与最初发布的问题相同。
            【解决方案8】:

            这适用于任何试图获取文件夹及其子文件夹中所有文件的列表并将其保存在文本文档中的人。 下面是完整的代码,包括“使用”语句、“命名空间”、“类”、“方法”等。 我尝试在整个代码中尽可能多地进行注释,以便您了解每个部分在做什么。 这将创建一个文本文档,其中包含任何给定根文件夹的所有文件夹和子文件夹中的所有文件的列表。毕竟,如果你不能用它做点什么,那么一个列表(比如在 Console.WriteLine 中)有什么用。 在这里,我在 C 盘上创建了一个名为“Folder1”的文件夹,并在其中创建了一个名为“Folder2”的文件夹。接下来,我用一堆文件、文件夹以及这些文件夹中的文件和文件夹填充了文件夹 2。 此示例代码将获取所有文件并在文本文档中创建一个列表并将该文本文档放在 Folder1 中。 注意:您不应该将文本文档保存到 Folder2(您正在读取的文件夹),这将是一种不好的做法。始终将其保存到另一个文件夹。
            我希望这可以帮助某人。

            using System;
            using System.IO;
            
            namespace ConsoleApplication4
            {
                class Program
                {
                    public static void Main(string[] args)
                    {
                        // Create a header for your text file
                        string[] HeaderA = { "****** List of Files ******" };
                        System.IO.File.WriteAllLines(@"c:\Folder1\ListOfFiles.txt", HeaderA);
            
                        // Get all files from a folder and all its sub-folders. Here we are getting all files in the folder
                        // named "Folder2" that is in "Folder1" on the C: drive. Notice the use of the 'forward and back slash'.
                        string[] arrayA = Directory.GetFiles(@"c:\Folder1/Folder2", "*.*", SearchOption.AllDirectories);
                        {
                            //Now that we have a list of files, write them to a text file.
                            WriteAllLines(@"c:\Folder1\ListOfFiles.txt", arrayA);
                        }
            
                        // Now, append the header and list to the text file.
                        using (System.IO.StreamWriter file =
                            new System.IO.StreamWriter(@"c:\Folder1\ListOfFiles.txt"))
                        {
                            // First - call the header 
                            foreach (string line in HeaderA)
                            {
                                file.WriteLine(line);
                            }
            
                            file.WriteLine(); // This line just puts a blank space between the header and list of files. 
            
            
                            // Now, call teh list of files.
                            foreach (string name in arrayA)
                            {
                                file.WriteLine(name);
                            }
            
                        }
                      }
            
            
                    // These are just the "throw new exception" calls that are needed when converting the array's to strings. 
            
                    // This one is for the Header.
                    private static void WriteAllLines(string v, string file)
                    {
                        //throw new NotImplementedException();
                    }
            
                    // And this one is for the list of files. 
                    private static void WriteAllLines(string v, string[] arrayA)
                    {
                        //throw new NotImplementedException();
                    }
            
            
            
                }
            }
            

            【讨论】:

              【解决方案9】:

              LINQ 解决方案:

              public IEnumerable<FileInfo> DirSearch(string sDir){
                          var directoryInfo = new DirectoryInfo(sDir);
                          return directoryInfo.GetDirectories()
                              .SelectMany(directory => directory.GetFiles());
              }
              

              这将返回 FileInfos 而不是字符串,因为我认为它们更易于使用。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-11-26
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-04-11
                • 1970-01-01
                相关资源
                最近更新 更多