Posted by Joe | Posted in C# | Posted on 21-10-2009
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 Console.WriteLine(i.ToFileSize());
And the result would be
76.8 MB



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.
Hi Alex
Fair point; I’ve updated the post accordingly.
Joe
[...] for sharing, I found this small code from this site and this is the easiest way for converting bytes (because I’m a Math guru who repeated [...]
HI Joe,
thanks for this information I use and work perfect.
Jose from Uruguay
Hi Jose
Glad it helped you.
Joe