如何在 C# 中获取目录中所有文件、子文件及其大小?
为了获取文件,C# 提供了一个方法 Directory.GetFiles
Directory.GetFiles 返回与指定搜索模式相匹配的,包括路径在内的所有文件名称,还可以选择搜索子目录。
在以下示例中,* 匹配该位置中零个或多个字符。
SearchOption TopDirectoryOnly. 仅搜索顶级目录
SearchOption AllDirectories. 搜索所有顶级目录和子目录
FileInfo 可以获取诸如长度、名称之类的文件信息
示例 1
static void Main (string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder"; var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories); foreach (string file in files) { Console.WriteLine(file); } Console.ReadLine (); }
输出
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain\TestFolderMain.txt C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1\TestFolderMain1.txt C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2\TestFolderMain2.txt C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2\TestFolderMainSubDirectory\TestFolderSubDirectory.txt
示例 2
static void Main (string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder"; var files = Directory.GetFiles(rootPath, "*.*", SearchOption.TopDirectoryOnly); foreach (string file in files) { Console.WriteLine(file); } Console.ReadLine (); }
输出
C:\Users\Koushik\Desktop\TestFolder\Topdirectory.txt
示例 3
static void Main (string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder"; var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories); foreach (string file in files) { var info = new FileInfo(file); Console.WriteLine($"{ Path.GetFileName(file) }: { info.Length } bytes"); } Console.ReadLine (); }
输出
Topdirectory.txt: 0 bytes TestFolderMain.txt: 0 bytes TestFolderMain1.txt: 10 bytes TestFolderMain2.txt: 20 bytes
广告