In order to get files, C# provides a method Directory.GetFiles
Directory.GetFilesReturns the names of all files (including their paths) ) matches the specified search pattern and optionally searches subdirectories.
In the following example, * matches zero or more characters in that position.
SearchOption TopDirectoryOnly. Search only top-level directories
SearchOption AllDirectories. Search all top-level directories and subdirectories
FileInfo Get file length, name and other information
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
The above is the detailed content of How to get all files, subfiles and their sizes in a directory in C#?. For more information, please follow other related articles on the PHP Chinese website!