Home >Backend Development >C#.Net Tutorial >How to get human-readable file size in bytes abbreviation using C#?
To get the directory, C# provides the Directory.GetDirectories method
Directory.GetDirectories returns the name of the subdirectory (including its path) in the specified directory that matches the specified search pattern ), and optionally search subdirectories
To obtain files, C# provides the Directory.GetFiles method
Directory.GetFiles returns the names (including their paths) of all files matching the specified search pattern , and can optionally search subdirectories
In order to obtain the file length, C# provides a property Length
static void Main(string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder"; var files = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories); foreach (string file in files) { long size = new FileInfo(file).Length / 1024; string humanKBSize = string.Format("{0} KB", size); string humanMBSize = string.Format("{0} MB", size / 1024); string humanGBSize = string.Format("{0} GB", size / 1024 / 1024); Console.WriteLine($"KB:{humanKBSize} MB:{humanMBSize} GB:{humanGBSize}"); } Console.ReadLine(); }
file C:\Users\Koushik\Desktop\TestFolder\Topdirectory.txt 22 KB 0 MB 0 GB file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain\TestFolderMain.txt 0 KB 2 MB 0 GB file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1\TestFolderMain1.txt 0 KB 0 MB 1 GB file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain1.txt 0 KB 0 MB 1 GB file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMain2.txt 0 KB 0 MB 1 GB file C:\Users\Koushik\Desktop\TestFolder\TestFolderMain2\TestFolderMainSubDirectory\TestFolderSubDirectory.txt 0 KB 0 MB 1 GB
The above is the detailed content of How to get human-readable file size in bytes abbreviation using C#?. For more information, please follow other related articles on the PHP Chinese website!