如何在C#目录中获取所有文件,子文件及其大小?
为了获取文件,C#提供了Directory.GetFiles方法。
Directory.GetFiles返回与指定搜索模式匹配的所有文件的名称(包括它们的路径),并有选择地搜索子目录。
在下面的示例中,*在该位置匹配零个或多个字符。
SearchOption仅TopDirectory。仅搜索顶部目录
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.txtC:\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 bytesTestFolderMain.txt: 0 bytes
TestFolderMain1.txt: 10 bytes
TestFolderMain2.txt: 20 bytes
以上是 如何在C#目录中获取所有文件,子文件及其大小? 的全部内容, 来源链接: utcz.com/z/338042.html