為了取得文件,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中文網其他相關文章!