Hello, All!
Специальный форматер для вывода размеров файлов (10КB, 1,5MB, etc).
Объединяя идеи
Гайдара и
Joshua Flanagan.
Использовать
class Program
{
static void Main(string[] args)
{
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs3}", 100));
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 2000));
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs1}", 30000000));
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", 400000000000));
}
}
Результат
File size: 100.000B
File size: 1.95KB
File size: 28.6MB
File size: 372.53GB
Исходник
using System;
using System.Text;
namespace Rsdn.Framework.Common
{
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (typeof(ICustomFormatter).IsAssignableFrom(formatType))
return this;
return null;
}
private const string fileSizeFormat = "fs";
private string[] letters = new string[] { "B", "KB", "MB", "GB", "TB", "PB" };
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (format == null || !format.StartsWith(fileSizeFormat))
{
return defaultFormat(format, arg, formatProvider);
}
Decimal size;
try
{
size = Convert.ToDecimal(arg);
}
catch (InvalidCastException)
{
return defaultFormat(format, arg, formatProvider);
}
byte i = 0;
while ((size >= 1024) && (i < letters.Length - 1))
{
i++;
size /= 1024;
}
string precision = format.Substring(2);
if (String.IsNullOrEmpty(precision)) precision = "2";
return String.Format("{0:N" + precision + "}{1}", size, letters[i]);
}
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();
}
}
}
Posted via RSDN NNTP Server 2.1 beta