Convert file size bytes to megabyte/gigabyte string using C#

I feel like I haven’t posted in ages. Have been busy changing job and moving house but I have a list of things I want to blog about soon.

Recently I needed to convert a number of bytes to a readable string that represents the number of kilobytes, megabytes or gigabytes.

I created an extension method for Int32 which does this for me Int64 as per Alex’s comment about the FileInfo.Length property being a long. I also changed my method for Int32 to call the other method so that it can be used for both int and long.


public static string ToFileSize(this int source)
    return ToFileSize(Convert.ToInt64(source));

public static string ToFileSize(this long source)
    const int byteConversion = 1024;
    double bytes = Convert.ToDouble(source);

    if (bytes >= Math.Pow(byteConversion, 3)) //GB Range
        return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 3), 2), " GB");
    else if (bytes >= Math.Pow(byteConversion, 2)) //MB Range
        return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 2), 2), " MB");
    else if (bytes >= byteConversion) //KB Range
        return string.Concat(Math.Round(bytes / byteConversion, 2), " KB");
    else //Bytes
        return string.Concat(bytes, " Bytes");

This can then be used like so:

i = 80530636; //76.8MB

And the result would be

76.8 MB

Download source

Posted on by Joe in C#

11 Responses to Convert file size bytes to megabyte/gigabyte string using C#

  1. Alex

    Although this example works perfectly I would dispute the logic of creating an extension method for Int32 when the FileInfo class property for length is a long.

  2. Joe

    Hi Alex

    Fair point; I’ve updated the post accordingly.


  3. Pingback: Filesize convertion in c# | My blog - Michael Angelo Yap

  4. Jose

    HI Joe,
    thanks for this information I use and work perfect.

    Jose from Uruguay

  5. Joe

    Hi Jose

    Glad it helped you.


  6. Darien

    Wonderful, that’s exactly what I was looking for! Your article just saved me alot of looking around

    I’ll make sure to put this in good use!

  7. rene noel

    i’m using jcreator lee..please help me how to convert bytes to kilobytes to megabytes to gigabytes using if-else statement in java..please…..

  8. Joe

    Hi Rene

    I haven’t written Java for about 10 years and don’t have an environment set up, but I’d imagine it will be pretty much the same.


  9. Reed

    Hi Joe,

    I am wondering why you wouldn’t just use 3 constants instead of calculating the power of a constant each time this method is run. Seems like overhead, especially if someone is depending on this method to run quickly.


  10. Joe

    Hi Reed

    It’s just sample blog code; no reason why you couldn’t use constants, and like you say it would give performance gains.


  11. .net dev

    works great.

Add a Comment