Skip to content

Instantly share code, notes, and snippets.

@EarMaster
Created June 19, 2019 10:54
Show Gist options
  • Save EarMaster/cde681fa6b7d6b307e8e7ed0d3847662 to your computer and use it in GitHub Desktop.
Save EarMaster/cde681fa6b7d6b307e8e7ed0d3847662 to your computer and use it in GitHub Desktop.
Formats a filesize into a human readable format. First parameter is filesize in bytes, second parameter is the precision of the resulting decimal number and the last parameter is the system (choose between 'decimal' aka SI-based or 'binary' based calculation).
public enum FileSizeSystem { Decimal, Binary }
public static string FormatFilesize (int Size) { return FormatFilesize(Size, 1, FileSizeSystem.Decimal); }
public static string FormatFilesize (int Size, int Decimals) { return FormatFilesize(Size, Decimals, FileSizeSystem.Decimal); }
public static string FormatFilesize (int Size, FileSizeSystem System) { return FormatFilesize(Size, 1, System); }
public static string FormatFilesize (int Size, int Decimals, FileSizeSystem SizeSystem) {
float OutputSize = (float)Size;
string[] Units;
switch (SizeSystem) {
case FileSizeSystem.Binary:
Units = new string[]{ "Byte", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" };
break;
case FileSizeSystem.Decimal:
default:
Units = new string[]{ "Byte", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
break;
}
int n;
for (n = 0; OutputSize > (SizeSystem == FileSizeSystem.Decimal ? 1000 : 1024); n++)
OutputSize /= (SizeSystem == FileSizeSystem.Decimal ? 1000 : 1024);
return OutputSize.ToString("N"+Decimals) + " " + Units.GetValue(n);
}
@EarMaster
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment