Convert number of bytes into a more "friendly" like string that display number of kB, MB or GB etc.
internal static class Extensions
{
// Unit specifications
private static string[][] byteUnits = new string[][]
{
new string[] { "bytes", "bytes" },
new string[] { "kB", "kilobyte" },
new string[] { "MB", "megabyte" },
new string[] { "GB", "gigabyte" },
new string[] { "TB", "terabyte" },
new string[] { "PB", "petabyte" },
new string[] { "EB", "exabyte" },
};
internal static string ToByteUnitString(this long byteCount, bool abbreviatedName = true)
{
int i = Convert.ToInt32(Math.Floor(Math.Log(byteCount, 2) / 10f));
if (i == 0)
return string.Format("{0} {1}", byteCount, (abbreviatedName) ? byteUnits[i][0] : byteUnits[i][1]);
return string.Format("{0:F2} {1}", byteCount / Math.Pow(1024, i), (abbreviatedName) ? byteUnits[i][0] : byteUnits[i][1]);
}
}
Example:
void Main()
{
var sizeString = new DriveInfo("C").AvailableFreeSpace.ToByteUnitString();
// test all units -- unit in abbreviated and normal
foreach (int i in Enumerable.Range(0, 6))
{
Console.WriteLine(((long)Math.Pow(1024, i)).ToByteUnitString(true));
Console.WriteLine(((long)Math.Pow(1024, i)).ToByteUnitString(false));
}
}
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


701
0




Mark 'bytes' tag as 'like'
Mark 'bytes' tag as 'ignore'