Convert Bytes To KB, MB In C#

C# FileInfo.Length returns the size of a file in bytes. This method coverts file size in bytes into KB, MB, GB, TB, or PB.

C# Convert Bytes To KB, MB, GB
 
C# FileInfo.Length returns the size of a file in bytes. This method coverts file size in bytes into KB, MB, GB, TB, or PB.
In one of my recent projects, I needed to restrict the maximum file size, i.e., 50MB. For this, I need to calculate the file size in MB. I found the code snippet here, https://stackoverflow.com/questions/37111511/getting-file-size-in-kb
 
I tweaked the code a little and created a static method.
 
I used this sample code to Get a File Size in C#
 
Data in computers is represented in bits, 0s and 1s. A byte is 8 bits. Each character is 1 byte. File size in computers is measured how much space in bytes it needs to store. The measurement of bytes is in x1024 (thousands).
 
Here is the table of data sizes.
 

Bytes

Abbreviation

Name

Binary

1024 bytes

1 KB

Kilobyte

2^10

1024 KB

1 MB

Megabyte

2^20

1024 MB

1 GB

Gigabyte

2^30

1024 GB

1 TB

Terabyte

2^40

1024 TB

1 PB

Petabyte

2^50

1024 PB

1 EB

Exabyte

2^60

1024 EB

1 ZB

Zettabyte

2^70

1024 ZB

1 YB

Yottabyte

2^80

 
To covert file size in MB, GB, TB etc., we just need to divide it by x1024 to find out the next name from the above table.
 
The following code example calculates a file size in KB, MB, GB etc. Each 1024 bytes is the next byte in size. Please make sure to change the file name to your own file. 
  1. using System;  
  2. using System.IO;  
  3. using System.Text;  
  4.   
  5. class Program  
  6. {  
  7. public static class FileSizeFormatter  
  8. {  
  9. // Load all suffixes in an array  
  10. static readonly string[] suffixes =  
  11. "Bytes""KB""MB""GB""TB""PB" };  
  12. public static string FormatSize(Int64 bytes)  
  13. {  
  14. int counter = 0;  
  15. decimal number = (decimal)bytes;  
  16. while (Math.Round(number / 1024) >= 1)  
  17. {  
  18. number = number / 1024;  
  19. counter++;  
  20. }  
  21. return string.Format("{0:n1}{1}", number, suffixes[counter]);  
  22. }  
  23. }  
  24. static void Main(string[] args)  
  25. {  
  26. // Full file name  
  27. string fileName = @"C:\Temp\OK.zip";  
  28. FileInfo fi = new FileInfo(fileName);  
  29.   
  30. if (fi.Exists)  
  31. {  
  32. string size = FileSizeFormatter.FormatSize(fi.Length);  
  33. Console.WriteLine(size);  
  34. }  
  35. Console.ReadKey();  
  36. }  
  37. }  
In the above code, FileInfo.Length returns the size of a file in number of bytes. FormatSize method divides total bytes by x1024 and finds the next abbreviation from the array.