为了获取文件,C#提供了Directory.GetFiles方法。
Directory.GetFiles返回与指定搜索模式匹配的所有文件的名称(包括它们的路径),并有选择地搜索子目录。
在下面的示例中,*在该位置匹配零个或多个字符。
SearchOption仅TopDirectory。仅搜索顶部目录
SearchOption AllDirectories。搜索所有顶级目录和子目录
FileInfo获取文件信息,如长度,名称
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
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
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