为了获取文件,C#提供了一个方法Directory.GetFiles
Directory.GetFiles返回所有文件的名称(包括它们的路径) ) 匹配指定的搜索模式,并可选择搜索子目录。
在下面的示例中,* 匹配该位置中的零个或多个字符。
SearchOption TopDirectoryOnly。仅搜索顶级目录
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
以上是如何在C#中获取目录中的所有文件、子文件及其大小?的详细内容。更多信息请关注PHP中文网其他相关文章!