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:
nice to see you write c#
Welcome to our c#lub!
Haha, I was expecting a comment like this from you :)
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));
}
Post a Comment