Tuesday, 13 April 2010

Format file size (C#)

This post is not spectacular, but might be useful for some of you. I wrote a simple function to format the file size like it is in the file explorer (21 KB, 1,23 MB etc). I needed this for showing the file size in a tooltip for a SharePoint treeview.


private string FileSizeFormat(long size)
{
const int KB = 1024;
const int MB = 1048576;
const int GB = 1073741824;

if (size < KB)
{
return string.Format("{0} bytes", size);
}
else if (size < MB)
{
return string.Format("{0} KB", (size / KB));
}
else if (size < GB)
{
return string.Format("{0:0.00} MB", (size / MB));
}
else
{
return string.Format("{0:0.00} GB", (size / GB));
}
}

Just enter the file size (which usually is a long) into this function, you get the appropriate format back.
Edit: Made the code a bit easier (thanks Frank!)

3 comments:

Frank said...

nice to see you write c#
Welcome to our c#lub!

Robje said...

Haha, I was expecting a comment like this from you :)

Frank said...

You could optimize this code a little:



if (size < KB)
{
return string.Format("{0} bytes", size);
}
else if (size < MB)
{
return string.Format("{0} KB", (size / KB));
}
else if (size < GB)
{
return string.Format("{0:0.00} MB", (size / MB));
}
else
{
return string.Format("{0:0.00} GB", (size / GB));
}