Dosya Boyutu Formatlama -- File Size Format
Selamlar, üzerinde çalıştığım bir projede dosyanın boyutuna göre kb, mb yada gb yazdırma ihtiyacı içerisine girdim. Bu nedenle aşağıda sizlerinde işine yarayabileceğini düşündüğüm bir kod ile karşılaştım. Yazmak yerine bunu alıp kullandım. Gayet güzel çalıştı. Umarım sizlerinde işine yarar.
Selamlar, üzerinde çalıştığım bir projede dosyanın boyutuna göre kb, mb yada gb yazdırma ihtiyacı içerisine girdim. Bu nedenle aşağıda sizlerinde işine yarayabileceğini düşündüğüm bir kod ile karşılaştım. Yazmak yerine bunu alıp kullandım. Gayet güzel çalıştı. Umarım sizlerinde işine yarar. Eğer Makalenin orjinaline ulaşmak isterseniz Tıklayın !
using System;
using System.Web;
namespace VeriMask.Web.Tools
{
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
private const string fileSizeFormat = "FF";
private const Decimal KiloByte = 1024M;
private const Decimal MegaByte = KiloByte * 1024M;
private const Decimal GigaByte = MegaByte * 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 > GigaByte)
{
size /= GigaByte;
suffix = "GB";
}
else if (size > MegaByte)
{
size /= MegaByte;
suffix = "MB";
}
else if (size > KiloByte)
{
size /= KiloByte;
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 formattable = _arg as IFormattable;
if (formattable != null)
return formattable.ToString(_format, _formatProvider);
return _arg.ToString();
}
public object GetFormat(Type _formatType)
{
if (_formatType == typeof(ICustomFormatter)) return this;
return null;
}
}
}

Ana Sayfa