C# Programming > Data

C# File Size From Bytes

c# filesize

File Size

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

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(int byteCount)
{
     string size = "0 Bytes";
     if (byteCount >= 1073741824)
          size = String.Format("{0:##.##}", byteCount / 1073741824) + " GB";
     else if (byteCount >= 1048576)
          //etc...

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. 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...

Download File-SIze Application C# Source Code

Back to C# Article List

License Agreement | Privacy Policy | Submit Link | Submit Article | Subscribe to Newsletter | Contact Us