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

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

    If you only need filenames and since I didn't really like most of the solutions here (feature-wise or readability-wise), how about this lazy one?

    private void Foo()
    {
      var files = GetAllFiles("pathToADirectory");
      foreach (string file in files)
      {
          // Use can use Path.GetFileName() or similar to extract just the filename if needed
          // You can break early and it won't still browse your whole disk since it's a lazy one
      }
    }
    
    /// The specified path is invalid (for example, it is on an unmapped drive).
    /// The caller does not have the required permission.
    ///  is a file name.-or-A network error has occurred.
    /// The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters and file names must be less than 260 characters.
    ///  is null.
    ///  is a zero-length string, contains only white space, or contains one or more invalid characters as defined by .
    [NotNull]
    public static IEnumerable GetAllFiles([NotNull] string directory)
    {
      foreach (string file in Directory.GetFiles(directory))
      {
        yield return file; // includes the path
      }
    
      foreach (string subDir in Directory.GetDirectories(directory))
      {
        foreach (string subFile in GetAllFiles(subDir))
        {
          yield return subFile;
        }
      }
    }
    

提交回复
热议问题