namespace Extensions { using System; using System.Globalization; using System.Threading; public static class FileSizeExtensions { public static string FormatFileSize( this long fileSize, Func 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 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 round, int decimals, RoundType roundType, double size) { return round == null ? (decimals > 0 ? Math.Round(size, decimals) : (ulong) size) : round(size, roundType, decimals); } } }