Skip to content

Instantly share code, notes, and snippets.

@UweKeim
Created October 27, 2020 07:45
Show Gist options
  • Save UweKeim/403b888aa39813390c5f9e4fb6e4f598 to your computer and use it in GitHub Desktop.
Save UweKeim/403b888aa39813390c5f9e4fb6e4f598 to your computer and use it in GitHub Desktop.
Automatically formatting an integer for human-readable file size
namespace Extensions
{
using System;
using System.Globalization;
using System.Threading;
public static class FileSizeExtensions
{
public static string FormatFileSize(
this long fileSize,
Func<double, RoundType, int, object> round = null)
{
return FormatFileSize((ulong) fileSize, round);
}
public enum RoundType
{
B,
KB,
MB,
GB,
TB
}
private static CultureInfo culture => Thread.CurrentThread.CurrentCulture;
public static string FormatFileSize(
this ulong fileSize,
Func<double, RoundType, int, object> round = null)
{
const long fileSize1KB = 1024;
const long fileSize100KB = 102400;
const long fileSize1MB = 1048576;
const long fileSize1GB = 1073741824;
const long fileSize1TB = 1099511627776;
if (fileSize < fileSize1KB)
{
return string.Format(
culture,
@"{0} {1}",
checkround(round, 0, RoundType.B, fileSize),
"Bytes");
}
else if (fileSize < fileSize100KB)
{
return string.Format(
culture,
@"{0} {1}",
checkround(round, 0, RoundType.KB, fileSize / (double) fileSize1KB),
"KB");
}
else if (fileSize < fileSize1MB)
{
return string.Format(
culture,
@"{0} {1}",
checkround(round, 0, RoundType.KB, (double) fileSize / fileSize1KB),
"KB");
}
else if (fileSize < fileSize1GB)
{
return string.Format(
culture,
@"{0} {1}",
checkround(round, 1, RoundType.MB, fileSize / (double) fileSize1MB),
"MB");
}
else if (fileSize < fileSize1TB)
{
return string.Format(
culture,
@"{0} {1}",
checkround(round, 1, RoundType.GB, fileSize / (double) fileSize1GB),
"GB");
}
else
{
return string.Format(
culture,
@"{0} {1}",
checkround(round, 2, RoundType.TB, fileSize / (double) fileSize1TB),
"TB");
}
}
private static object checkround(
Func<double, RoundType, int, object> round,
int decimals,
RoundType roundType,
double size)
{
return round == null
? (decimals > 0 ? Math.Round(size, decimals) : (ulong) size)
: round(size, roundType, decimals);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment