File Size C Sharp

C# File Size From Bytes

What is File Size

A file size is the measurement of the area of a file on a storage device, like a hard disk. We can measure file sizes in bytes (B),Kilobytes (KB), Megabytes (MB), Gigabytes (GB), Terabytes (TB), etc ..

The column size is sorted for the largest file first in the image below of the files listed in the Windows Explorer.

As can be seen, the first file "Yamunotri" typee of "JPG File" has a file size of 904 KB. In this image the smallest file is 36 KB in size.

 File Size C Shap Example_UK-Academe

Get File-Size

Any file has a file size. C # is excellent to read byte count files. We need a few statements to get a readable file size (2 kb, 3 mb, etc.).

File Size Table

You basically need a simple file size table:




1024 KB  Kilobyte
1048576 (1024 * 1024) MB  Megabyte
1073741824 (1024 * 1024 * 1024) GB  Gigabyte
1099511627776 (1024 * 1024 * 1024*1024)  TB  Terabyte
 1024 TB or (1024)5  PB  Petabyte


To convert a byte count (byte array length) into a readable file size estimate, you can use table above. Check the byte count backwards. First we can check if the byte is in the gigabyte range, then within the megabyte, then in kilobyte..

For example, Here's some C# code:

private string GetFileSize(double byteCount)
            string size = "0 Bytes";
            if (byteCount >= 1073741824.0)
                size = String.Format("{0:##.##}", byteCount / 1073741824.0) + " GB";
            else if(byteCount>=1048576.0)
                size = String.Format("{0:##.##}", byteCount / 1048576.0) + " MB";
            else if (byteCount >= 1024.0)
                size = String.Format("{0:##.##}", byteCount / 1024.0) + " KB";
            else if (byteCount >0 && byteCount<1024.0)
                size = byteCount.ToString()+ " Bytes";
            return size;


Notice that the additional step is to format a 00.00 style file size. Download the full function source code at the bottom of the page.

The Source Code

To get an impression of how it works, download example C #, source code included. Keep in mind that the file size is more of an estimate of the size of the image and is usually designed to help people read the images. This means that it can easily be transmitted into almost any other programming language, that it does not have to be C #.


Download Source Code


Video Tutorial