Convert Bytes To KB, MB In C#

C# Convert Bytes To KiloBytes (KB), MegaBytes (MB), GigaBytes (GB), and TereBytes (TB)

C# FileInfo.Length returns the size of a file in bytes. The method I share below converts file size in bytes into KB, MB, GB, TB, or PB. You can use this method to validate file sizes or just convert a file size from bytes to KB, KB to MB or MB to GB or GB to TB, etc. It will help you convert from simple bytes to any of the common-size units. You could even use it to as an MB to KB converter if you need to use a smaller unit.

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 by 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 convert file size into 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, TB, etc. Every 1024 bytes is the next byte in size. Please make sure to change the file name to your own file. 

using System;  
using System.IO;  
using System.Text;  
  
class Program  
{  
public static class FileSizeFormatter  
{  
// Load all suffixes in an array  
static readonly string[] suffixes =  
{ "Bytes", "KB", "MB", "GB", "TB", "PB" };  
public static string FormatSize(Int64 bytes)  
{  
int counter = 0;  
decimal number = (decimal)bytes;  
while (Math.Round(number / 1024) >= 1)  
{  
number = number / 1024;  
counter++;  
}  
return string.Format("{0:n1}{1}", number, suffixes[counter]);  
}  
}  
static void Main(string[] args)  
{  
// Full file name  
string fileName = @"C:\Temp\OK.zip";  
FileInfo fi = new FileInfo(fileName);  
  
if (fi.Exists)  
{  
string size = FileSizeFormatter.FormatSize(fi.Length);  
Console.WriteLine(size);  
}  
Console.ReadKey();  
}  
}

In the above code, FileInfo.Length returns the size of a file in the number of bytes. FormatSize method divides total bytes by x1024 and finds the next abbreviation from the array.


Recommended Free Ebook
Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.