public static string ToAbbreviatedFileSize(this decimal lengthInBytes, int maxPrecision = 2, FileSizeUnitAbbreviation? fileSizeUnitAbbreviation = null) { if (maxPrecision < 0) throw new ArgumentOutOfRangeException("maxPrecision", "Must be greater than or equal to zero."); var unit = fileSizeUnitAbbreviation ?? GetSmartUnitAbbreviation(lengthInBytes); var size = lengthInBytes.ConvertBytesTo(unit); var precision = size.GetPrecision(maxPrecision); var sizeText = size.ToString(precision.GetSizeFormat()); return string.Format("{0} {1}", sizeText, unit); }
private static decimal ConvertBytesTo(this decimal lengthInBytes, FileSizeUnitAbbreviation unitAbbreviation) { switch (unitAbbreviation) { case FileSizeUnitAbbreviation.B: return lengthInBytes; case FileSizeUnitAbbreviation.Kb: return lengthInBytes / Factor; case FileSizeUnitAbbreviation.Mb: return lengthInBytes / Factor / Factor; case FileSizeUnitAbbreviation.Gb: return lengthInBytes / Factor / Factor / Factor; case FileSizeUnitAbbreviation.Tb: return lengthInBytes / Factor / Factor / Factor / Factor; case FileSizeUnitAbbreviation.Pb: return lengthInBytes / Factor / Factor / Factor / Factor / Factor; default: return lengthInBytes / Factor / Factor / Factor / Factor / Factor / Factor; } }
private static decimal ConvertBytesTo(this decimal lengthInBytes, FileSizeUnitAbbreviation unitAbbreviation) { switch (unitAbbreviation) { case FileSizeUnitAbbreviation.B: return(lengthInBytes); case FileSizeUnitAbbreviation.Kb: return(lengthInBytes / Factor); case FileSizeUnitAbbreviation.Mb: return(lengthInBytes / Factor / Factor); case FileSizeUnitAbbreviation.Gb: return(lengthInBytes / Factor / Factor / Factor); case FileSizeUnitAbbreviation.Tb: return(lengthInBytes / Factor / Factor / Factor / Factor); case FileSizeUnitAbbreviation.Pb: return(lengthInBytes / Factor / Factor / Factor / Factor / Factor); default: return(lengthInBytes / Factor / Factor / Factor / Factor / Factor / Factor); } }
public static string ToAbbreviatedFileSize(this long lengthInBytes, int maxPrecision = 2, FileSizeUnitAbbreviation? fileSizeUnitAbbreviation = null) { return ((decimal)lengthInBytes).ToAbbreviatedFileSize(maxPrecision, fileSizeUnitAbbreviation); }