Thanks to JLRishe's answer. Here is my edited code for your convenience.
public static class QuickImgSize
{
//https://mcmap.net/q/81994/-does-net-provide-an-easy-way-convert-bytes-to-kb-mb-gb-etc
private static string[] S_SIZE_SUFFIXES =
{ "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
private static string SizeSuffix(long value, int decimalPlaces = 2)
{
if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
if (value < 0) { return "-" + SizeSuffix(-value, decimalPlaces); }
if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }
// mag is 0 for bytes, 1 for KB, 2, for MB, etc.
int mag = (int)Math.Log(value, 1024);
// 1L << (mag * 10) == 2 ^ (10 * mag)
// [i.e. the number of bytes in the unit corresponding to mag]
decimal adjustedSize = (decimal)value / (1L << (mag * 10));
// make adjustment when the value is large enough that
// it would round up to 1000 or more
if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
{
mag += 1;
adjustedSize /= 1024;
}
return string.Format("{0:n" + decimalPlaces + "} {1}",
adjustedSize,
S_SIZE_SUFFIXES[mag]);
}
public static string GetFileSize(string szPath)
{
var fileInfo = new FileInfo(szPath);
return SizeSuffix(fileInfo.Length);
}
}
Usage:
Console.WriteLine(QuickImgSize.GetFileSize(@"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"));