Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

FileSizeFormatProvider - C#

RSS
Modified on Wed, Nov 12, 2014, 10:26 AM by Administrator Categorized as ┬ĚNet Framework

Format Provider

public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        return (formatType == typeof(ICustomFormatter)) ? this : null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        var prefixes = "KMGTPEZY";
        double input = Convert.ToDouble(arg);
        var imax = prefixes.Length - 1;
        var prefix = string.Empty;

        for (var i = 0; i <= imax; i++)
        {
            if (input < 1024)
                break;

            input /= 1024.0;
            prefix = prefixes[i].ToString();
        }

        var result = string.Format("{0:" + format + "} {1}B", input, prefix);

        return result;
    }
}

Unit Tests

[TestClass]
public class FileSizeFormatProviderTests
{
    [TestMethod]
    public void TestFileSizeFormatProvider()
    {
        long fileSize = 1453178961; // 1,453,178,961
        string s = string.Empty;
        var fp = new FileSizeFormatProvider();

        s = string.Format(fp, "{0:0.000}", 1453178961);
        Assert.AreEqual("1.353 GB", s);

        s = string.Format(fp, "{0:0.000}", 1453164278961);
        Assert.AreEqual("1.322 TB", s);

        s = string.Format(fp, "{0:0.000}", 531453164278961); //531,453,164,278,961
        Assert.AreEqual("483.354 TB", s);

        s = string.Format(fp, "{0:0.000}", 6531453996164278); //6,531,453,996,164,278
        Assert.AreEqual("5.801 PB", s);

        s = string.Format(fp, "{0:0.000}", 6531453996164278961); //6,531,453,996,164,278,961
        Assert.AreEqual("5.665 EB", s);

    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.