Jan 14, 2009

File Size Formatting in C#

Have you ever wanted to display the size of the file in bytes, kilo bytes or mega bytes, here is a simple code snippet to do that.


private string FormatSize (double fileSize)
{
if (fileSize < 1024)
return String.Format(”{0:N0} B”, fileSize);
else if (fileSize < 1024*1024)
return String.Format(”{0:N2} KB”, fileSize/1024);
else
return String.Format(”{0:N2} MB”, fileSize/(1024*1024));
}