Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I use this one, I get it from the web</p> <pre><code>public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; return null; } private const string fileSizeFormat = "fs"; private const Decimal OneKiloByte = 1024M; private const Decimal OneMegaByte = OneKiloByte * 1024M; private const Decimal OneGigaByte = OneMegaByte * 1024M; public string Format(string format, object arg, IFormatProvider formatProvider) { if (format == null || !format.StartsWith(fileSizeFormat)) { return defaultFormat(format, arg, formatProvider); } if (arg is string) { return defaultFormat(format, arg, formatProvider); } Decimal size; try { size = Convert.ToDecimal(arg); } catch (InvalidCastException) { return defaultFormat(format, arg, formatProvider); } string suffix; if (size &gt; OneGigaByte) { size /= OneGigaByte; suffix = "GB"; } else if (size &gt; OneMegaByte) { size /= OneMegaByte; suffix = "MB"; } else if (size &gt; OneKiloByte) { size /= OneKiloByte; suffix = "kB"; } else { suffix = " B"; } string precision = format.Substring(2); if (String.IsNullOrEmpty(precision)) precision = "2"; return String.Format("{0:N" + precision + "}{1}", size, suffix); } private static string defaultFormat(string format, object arg, IFormatProvider formatProvider) { IFormattable formattableArg = arg as IFormattable; if (formattableArg != null) { return formattableArg.ToString(format, formatProvider); } return arg.ToString(); } } </code></pre> <p>an example of use would be:</p> <pre><code>Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 100)); Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 10000)); </code></pre> <p>Credits for <a href="http://flimflan.com/blog/FileSizeFormatProvider.aspx" rel="noreferrer">http://flimflan.com/blog/FileSizeFormatProvider.aspx</a></p> <p>There is a problem with ToString(), it's expecting a NumberFormatInfo type that implements IFormatProvider but the NumberFormatInfo class is sealed :( </p> <p>If you're using C# 3.0 you can use an extension method to get the result you want:</p> <pre><code>public static class ExtensionMethods { public static string ToFileSize(this long l) { return String.Format(new FileSizeFormatProvider(), "{0:fs}", l); } } </code></pre> <p>You can use it like this.</p> <pre><code>long l = 100000000; Console.WriteLine(l.ToFileSize()); </code></pre> <p>Hope this helps.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload