roadie/Roadie.Api.Library/Utility/FileSizeFormatProvider.cs

80 lines
2.3 KiB
C#
Raw Normal View History

2018-11-04 15:16:52 +00:00
using System;
namespace Roadie.Library.Utility
{
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
private const string fileSizeFormat = "fs";
2018-11-04 20:33:37 +00:00
2019-07-03 16:21:29 +00:00
private const decimal OneGigaByte = OneMegaByte * 1024M;
2018-11-04 20:33:37 +00:00
2019-07-03 16:21:29 +00:00
private const decimal OneKiloByte = 1024M;
2018-11-04 20:33:37 +00:00
2019-07-03 16:21:29 +00:00
private const decimal OneMegaByte = OneKiloByte * 1024M;
2018-11-04 20:33:37 +00:00
2019-07-03 16:21:29 +00:00
private const decimal OneTeraByte = OneGigaByte * 1024M;
2018-11-04 15:16:52 +00:00
public string Format(string format, object arg, IFormatProvider formatProvider)
{
2019-07-03 16:21:29 +00:00
if (format == null || !format.StartsWith(fileSizeFormat)) return defaultFormat(format, arg, formatProvider);
2018-11-04 15:16:52 +00:00
2019-07-03 16:21:29 +00:00
if (arg is string) return defaultFormat(format, arg, formatProvider);
2018-11-04 15:16:52 +00:00
2019-07-03 16:21:29 +00:00
decimal size;
2018-11-04 15:16:52 +00:00
try
{
size = Convert.ToDecimal(arg);
}
catch (InvalidCastException)
{
return defaultFormat(format, arg, formatProvider);
}
string suffix;
if (size > OneTeraByte)
{
size /= OneTeraByte;
suffix = "TB";
}
else 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";
}
2019-07-03 16:21:29 +00:00
var precision = format.Substring(2);
if (string.IsNullOrEmpty(precision)) precision = "2";
2018-11-04 20:33:37 +00:00
2019-07-03 16:21:29 +00:00
return string.Format("{0:N" + precision + "}{1}", size, suffix);
2018-11-04 20:33:37 +00:00
}
2018-11-04 15:16:52 +00:00
2018-11-04 20:33:37 +00:00
public object GetFormat(Type formatType)
{
2019-07-03 16:21:29 +00:00
if (formatType == typeof(ICustomFormatter)) return this;
2018-11-04 20:33:37 +00:00
return null;
2018-11-04 15:16:52 +00:00
}
private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)
{
2019-07-03 16:21:29 +00:00
var formattableArg = arg as IFormattable;
if (formattableArg != null) return formattableArg.ToString(format, formatProvider);
2018-11-04 15:16:52 +00:00
return arg.ToString();
}
}
2018-11-04 20:33:37 +00:00
}