C# Programming > Data

C# File Size From Bytes

c# filesize

Get File-Size

Any file has a file size. C# is very good at reading files for the byte count. In order to get file size that is readable (2 kb, 3 mb, etc.) you need to use a few if statements.

File Size Table

You basically need a simple file size table:

1024 KB
1048576 (1024 * 1024) MB
1073741824 (1024 * 1024 * 1024) GB

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 see if it is within the gigabyte range, then within the megabyte, then kilobyte, and finally just returns the same byte count as "Bytes".

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)

     return size;

Notice the extra step is to format the file size to a 00.00 style. For the full function, download the source code at the bottom of the page.

The Source Code

Download the example C# application, source code included, to have a feel at how it works. Keep in mind the file size is more of a big picture estimate and is usually designed for human readability.

Also notice that the source code is one big if statement used to get file size. That means you can easily port it to almost any other programming language, does not have to be C#. In other words it's a simple function for handling file size.

Back to C# Article List