问题描述
有没有什么简单的方法可以创建一个使用 IFormatProvider 的类来写出用户友好的文件大小?
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
otepad.exe");
long size = info.Length;
string sizeString = size.ToString(FileSizeFormatProvider); // This is where the class does its magic...
}
它应该产生格式为2,5 MB"、3,9 GB"、670 字节"的字符串等等.
It should result in strings formatted something like "2,5 MB", "3,9 GB", "670 bytes" and so on.
推荐答案
我用这个,我从网上弄的
I use this one, I get it from the web
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 类是密封的:(
There is a problem with ToString(), it's expecting a NumberFormatInfo type that implements IFormatProvider but the NumberFormatInfo class is sealed :(
如果你使用的是 C# 3.0,你可以使用扩展方法来获得你想要的结果:
If you're using C# 3.0 you can use an extension method to get the result you want:
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());
希望这会有所帮助.
这篇关于文件大小格式提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!