Is there any easy way to create a class that uses IFormatProvider that writes out a user-friendly file-size?
public static string GetFileSizeString(string filePath)
{
FileInfo info = new FileInfo(@"c:\windows\notepad.exe");
long size = info.Length;
string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic...
}
It should result in strings formatted something like "2,5 MB", "3,9 GB", "670 bytes" and so on.
Answer 1:
我用这一个,我把它从网络
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 > OneGigaByte)
{
size /= OneGigaByte;
suffix = "GB";
}
else if (size > OneMegaByte)
{
size /= OneMegaByte;
suffix = "MB";
}
else if (size > 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();
}
}
使用的一个例子是:
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 100));
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 10000));
学分http://flimflan.com/blog/FileSizeFormatProvider.aspx
有一个与toString()方法,该公司预计实现的IFormatProvider不过的NumberFormatInfo类是密封的NumberFormatInfo类型的问题:(
如果您正在使用C#3.0,你可以使用扩展方法来得到你想要的结果:
public static class ExtensionMethods
{
public static string ToFileSize(this long l)
{
return String.Format(new FileSizeFormatProvider(), "{0:fs}", l);
}
}
您可以使用它像这样。
long l = 100000000;
Console.WriteLine(l.ToFileSize());
希望这可以帮助。
Answer 2:
好的,我不会把它包装起来的格式提供,但不是重新发明轮子有一个Win32 API调用格式化基础上,我已经在不同的应用中多次使用附带的字节大小的字符串。
[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
public static extern long StrFormatByteSize( long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize );
所以,我想你应该能够放在一起使用供应商为核心的转换代码。
这里有一个链接到MSDN规范的StrFormatByteSize。
Answer 3:
我现在认识到你是实实在在的东西,会用的String.Format()工作 - 我想我应该张贴;-)前阅读问题两倍
我不喜欢,你必须在格式提供每一次明确地传递解决方案-从什么我可以从收集这篇文章 ,以接近这一点的最好办法,是实现文件大小类型,实现IFormattable接口。
我继续实施支持该接口的一个结构,并且可以从一个整数施放。 在我自己的文件相关的API,我将我.FileSize属性返回一个文件大小的实例。
下面的代码:
using System.Globalization;
public struct FileSize : IFormattable
{
private ulong _value;
private const int DEFAULT_PRECISION = 2;
private static IList<string> Units;
static FileSize()
{
Units = new List<string>(){
"B", "KB", "MB", "GB", "TB"
};
}
public FileSize(ulong value)
{
_value = value;
}
public static explicit operator FileSize(ulong value)
{
return new FileSize(value);
}
override public string ToString()
{
return ToString(null, null);
}
public string ToString(string format)
{
return ToString(format, null);
}
public string ToString(string format, IFormatProvider formatProvider)
{
int precision;
if (String.IsNullOrEmpty(format))
return ToString(DEFAULT_PRECISION);
else if (int.TryParse(format, out precision))
return ToString(precision);
else
return _value.ToString(format, formatProvider);
}
/// <summary>
/// Formats the FileSize using the given number of decimals.
/// </summary>
public string ToString(int precision)
{
double pow = Math.Floor((_value > 0 ? Math.Log(_value) : 0) / Math.Log(1024));
pow = Math.Min(pow, Units.Count - 1);
double value = (double)_value / Math.Pow(1024, pow);
return value.ToString(pow == 0 ? "F0" : "F" + precision.ToString()) + " " + Units[(int)pow];
}
}
并演示如何工作的一个简单的单元测试:
[Test]
public void CanUseFileSizeFormatProvider()
{
Assert.AreEqual(String.Format("{0}", (FileSize)128), "128 B");
Assert.AreEqual(String.Format("{0}", (FileSize)1024), "1.00 KB");
Assert.AreEqual(String.Format("{0:0}", (FileSize)10240), "10 KB");
Assert.AreEqual(String.Format("{0:1}", (FileSize)102400), "100.0 KB");
Assert.AreEqual(String.Format("{0}", (FileSize)1048576), "1.00 MB");
Assert.AreEqual(String.Format("{0:D}", (FileSize)123456), "123456");
// You can also manually invoke ToString(), optionally with the precision specified as an integer:
Assert.AreEqual(((FileSize)111111).ToString(2), "108.51 KB");
}
正如你所看到的,文件大小类型现在可以正确的格式,并且还可以指定小数位数,以及如果需要,将定期数字格式。
我想你可以更进一步借此,例如允许明确的格式选择,例如,“{0:KB}”给力的千字节格式。 但我要离开它在这一点。
我也留下下面我最初的职位这两个不喜欢使用的格式API ...
100种对皮肤一只猫,但这里是我的方法 - 添加一个扩展方法为int类型:
public static class IntToBytesExtension
{
private const int PRECISION = 2;
private static IList<string> Units;
static IntToBytesExtension()
{
Units = new List<string>(){
"B", "KB", "MB", "GB", "TB"
};
}
/// <summary>
/// Formats the value as a filesize in bytes (KB, MB, etc.)
/// </summary>
/// <param name="bytes">This value.</param>
/// <returns>Filesize and quantifier formatted as a string.</returns>
public static string ToBytes(this int bytes)
{
double pow = Math.Floor((bytes>0 ? Math.Log(bytes) : 0) / Math.Log(1024));
pow = Math.Min(pow, Units.Count-1);
double value = (double)bytes / Math.Pow(1024, pow);
return value.ToString(pow==0 ? "F0" : "F" + PRECISION.ToString()) + " " + Units[(int)pow];
}
}
有了这个扩展在汇编,格式化文件大小,只需使用类似(1234567).ToBytes声明()
下面MbUnit的测试澄清恰恰是输出如下:
[Test]
public void CanFormatFileSizes()
{
Assert.AreEqual("128 B", (128).ToBytes());
Assert.AreEqual("1.00 KB", (1024).ToBytes());
Assert.AreEqual("10.00 KB", (10240).ToBytes());
Assert.AreEqual("100.00 KB", (102400).ToBytes());
Assert.AreEqual("1.00 MB", (1048576).ToBytes());
}
你可以很容易地改变单位和精度,以任何适合您的需求:-)
Answer 4:
这是我所知道的格式文件大小最简单的实现:
public string SizeText
{
get
{
var units = new[] { "B", "KB", "MB", "GB", "TB" };
var index = 0;
double size = Size;
while (size > 1024)
{
size /= 1024;
index++;
}
return string.Format("{0:2} {1}", size, units[index]);
}
}
而大小是以字节为单位未格式化的文件大小。
基督教的问候
http://www.wpftutorial.net
Answer 5:
我的代码...感谢肖恩·奥斯汀。
[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
public static extern long StrFormatByteSize(long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize);
public void getFileInfo(string filename)
{
System.IO.FileInfo fileinfo = new FileInfo(filename);
this.FileName.Text = fileinfo.Name;
StringBuilder buffer = new StringBuilder();
StrFormatByteSize(fileinfo.Length, buffer, 100);
this.FileSize.Text = buffer.ToString();
}
Answer 6:
因为换档是一个非常便宜的操作
public static string ToFileSize(this long size)
{
if (size < 1024)
{
return (size).ToString("F0") + " bytes";
}
else if ((size >> 10) < 1024)
{
return (size/(float)1024).ToString("F1") + " KB";
}
else if ((size >> 20) < 1024)
{
return ((size >> 10) / (float)1024).ToString("F1") + " MB";
}
else if ((size >> 30) < 1024)
{
return ((size >> 20) / (float)1024).ToString("F1") + " GB";
}
else if ((size >> 40) < 1024)
{
return ((size >> 30) / (float)1024).ToString("F1") + " TB";
}
else if ((size >> 50) < 1024)
{
return ((size >> 40) / (float)1024).ToString("F1") + " PB";
}
else
{
return ((size >> 50) / (float)1024).ToString("F0") + " EB";
}
}
Answer 7:
我需要可以定位的不同文化版本(小数点分隔符,“字节”翻译),并支持所有可能的二进制前缀 (最多了Exa)。 下面是一个说明如何使用它的例子:
// force "en-US" culture for tests
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(1033);
// Displays "8.00 EB"
Console.WriteLine(FormatFileSize(long.MaxValue));
// Use "fr-FR" culture. Displays "20,74 ko", o is for "octet"
Console.WriteLine(FormatFileSize(21234, "o", null, CultureInfo.GetCultureInfo(1036)));
这里是代码:
/// <summary>
/// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes or exabytes, depending on the size
/// </summary>
/// <param name="size">The size.</param>
/// <returns>
/// The number converted.
/// </returns>
public static string FormatFileSize(long size)
{
return FormatFileSize(size, null, null, null);
}
/// <summary>
/// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, gigabytes, terabytes, petabytes or exabytes, depending on the size
/// </summary>
/// <param name="size">The size.</param>
/// <param name="byteName">The string used for the byte name. If null is passed, "B" will be used.</param>
/// <param name="numberFormat">The number format. If null is passed, "N2" will be used.</param>
/// <param name="formatProvider">The format provider. May be null to use current culture.</param>
/// <returns>The number converted.</returns>
public static string FormatFileSize(long size, string byteName, string numberFormat, IFormatProvider formatProvider)
{
if (size < 0)
throw new ArgumentException(null, "size");
if (byteName == null)
{
byteName = "B";
}
if (string.IsNullOrEmpty(numberFormat))
{
numberFormat = "N2";
}
const decimal K = 1024;
const decimal M = K * K;
const decimal G = M * K;
const decimal T = G * K;
const decimal P = T * K;
const decimal E = P * K;
decimal dsize = size;
string suffix = null;
if (dsize >= E)
{
dsize /= E;
suffix = "E";
}
else if (dsize >= P)
{
dsize /= P;
suffix = "P";
}
else if (dsize >= T)
{
dsize /= T;
suffix = "T";
}
else if (dsize >= G)
{
dsize /= G;
suffix = "G";
}
else if (dsize >= M)
{
dsize /= M;
suffix = "M";
}
else if (dsize >= K)
{
dsize /= K;
suffix = "k";
}
if (suffix != null)
{
suffix = " " + suffix;
}
return string.Format(formatProvider, "{0:" + numberFormat + "}" + suffix + byteName, dsize);
}
Answer 8:
这里是一个更精确的延伸:
public static string FileSizeFormat(this long lSize)
{
double size = lSize;
int index = 0;
for(; size > 1024; index++)
size /= 1024;
return size.ToString("0.000 " + new[] { "B", "KB", "MB", "GB", "TB" }[index]);
}
Answer 9:
域驱动方法可以在这里找到: https://github.com/Corniel/Qowaiv/blob/master/src/Qowaiv/IO/StreamSize.cs
该streamsize可结构是一个流大小的表示,可以让你既可以用适当的扩展格式的自动的,但也可以指定你想在KB / MB或什么的。 这有很多好处,不仅是因为你得到的格式开箱即用,它也可以帮助你做出更好的模型,因为它比明显,该属性或方法的结果代表了流大小。 它还具有对文件大小的扩展:GetStreamSize(此FileInfo的文件)。
短符号
- 新streamsize可(8900)的ToString( “S”)=> 8900b
- 新streamsize可(238900)的ToString( “S”)=> 238.9kb
- 新streamsize可(238900)的ToString( “S”)=> 238.9 KB
- 新streamsize可(238900)的ToString( “0000.00 S”)=> 0238.90 KB
全符号
- 新streamsize可(8900)的ToString( “0.0 F”)=> 8900.0字节
- 新streamsize可(238900)的ToString( “0 F”)=> 234千字节
- 新streamsize可(1238900)的ToString( “0.00 F”)=> 1.24兆字节
习惯
- 新streamsize可(8900)的ToString( “0.0 kb的”)=> 8.9 kb的
- 新streamsize可(238900)的ToString( “0.0 MB”)=> 0.2 MB
- 新streamsize可(1238900)的ToString( “#,## 0.00千字节”)=> 1,239.00千字节
- 新streamsize可(1238900)的ToString( “#,## 0”)=> 1238900
有一个的NuGet包,所以你才可以使用一个: https://www.nuget.org/packages/Qowaiv
Answer 10:
我已经采取了爱德华多的答案,并从其他地方类似的例子,以提供格式化的其他选项结合它。
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 string kiloByteFormat = "KB";
private const string megaByteFormat = "MB";
private const string gigaByteFormat = "GB";
private const string byteFormat = "B";
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)
{
//
// Ensure the format provided is supported
//
if (String.IsNullOrEmpty(format) || !(format.StartsWith(fileSizeFormat, StringComparison.OrdinalIgnoreCase) ||
format.StartsWith(kiloByteFormat, StringComparison.OrdinalIgnoreCase) ||
format.StartsWith(megaByteFormat, StringComparison.OrdinalIgnoreCase) ||
format.StartsWith(gigaByteFormat, StringComparison.OrdinalIgnoreCase)))
{
return DefaultFormat(format, arg, formatProvider);
}
//
// Ensure the argument type is supported
//
if (!(arg is long || arg is decimal || arg is int))
{
return DefaultFormat(format, arg, formatProvider);
}
//
// Try and convert the argument to decimal
//
Decimal size;
try
{
size = Convert.ToDecimal(arg);
}
catch (InvalidCastException)
{
return DefaultFormat(format, arg, formatProvider);
}
//
// Determine the suffix to use and convert the argument to the requested size
//
string suffix;
switch (format.Substring(0, 2).ToUpper())
{
case kiloByteFormat:
size = size / oneKiloByte;
suffix = kiloByteFormat;
break;
case megaByteFormat:
size = size / oneMegaByte;
suffix = megaByteFormat;
break;
case gigaByteFormat:
size = size / oneGigaByte;
suffix = gigaByteFormat;
break;
case fileSizeFormat:
if (size > oneGigaByte)
{
size /= oneGigaByte;
suffix = gigaByteFormat;
}
else if (size > oneMegaByte)
{
size /= oneMegaByte;
suffix = megaByteFormat;
}
else if (size > oneKiloByte)
{
size /= oneKiloByte;
suffix = kiloByteFormat;
}
else
{
suffix = byteFormat;
}
break;
default:
suffix = byteFormat;
break;
}
//
// Determine the precision to use
//
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();
}
}
Answer 11:
如果更改:
if (String.IsNullOrEmpty(precision))
{
precision = "2";
}
成
if (String.IsNullOrEmpty(precision))
{
if (size < 10)
{
precision = "2";
}
else if (size < 100)
{
precision = "1";
}
else
{
precision = "0";
}
}
无需额外的精度说明符的结果(所以只是0:FS而不是0:FS3)将开始通过调整精度尺寸模仿的Win32的StrFormatByteSize()。
文章来源: File-size format provider