How do I get a human-readable file size in bytes abbreviation using C#?


To get the directories C# provides a method Directory.GetDirectories

Directory.GetDirectories returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.

To get the files, C# provides a method Directory.GetFiles

Directory.GetFiles returns the names of all the files (including their paths) that match the specified search pattern, and optionally searches subdirectories

To get the file length , C# provides a property Length

Example

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();
}

Output

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

Updated on: 25-Nov-2020

317 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements