C# 返回位于其中包含文件夹的目录中的所有文件

C# returning all files located in a directory which has folders in it

如何检索包含文件、子文件夹和该文件夹中文件的目录中的所有文件。

注意: folder/files 不是常量

您可以使用 DirectoryInfo.GetFiles method with the RecurseSubdirectories 选项。

using System.IO;

FileInfo[] files 
    = new DirectoryInfo(@"C:\Program Files")
    .GetFiles("*", new EnumerationOptions { RecurseSubdirectories = true });

如果您不需要完整的文件列表,枚举目录的内容可能会更快。

using System.IO;
using System.Collections.Generic;
using System.Linq;

var directory = new DirectoryInfo(@"C:\Program Files");
IEnumerable<FileInfo> files 
    = from file in directory.EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true })
      where file.Name = "target.txt"
      select file;

foreach (FileInfo file in files)
{
    //...
}
                           

您可以使用Directory.GetFiles(path) and Directory.GetDirectories(path)

static void ScanDir(string path, int spaces = 0)
{
    var files = Directory.GetFiles(path);
    foreach (var file in files)
    {
        for (int i = 0; i < spaces; i++)
            Console.Write(" "); // Just for styling

        Console.WriteLine(file);
    }

    var dirs = Directory.GetDirectories(path);
    foreach (var dir in dirs)
    {
        ScanDir(dir, spaces + 4);
    }
}


static void Main()
{
    ScanDir("C:\path\to");
}