Long Extensions - SaintOswald/SaintOswald.Libraries.Extensions GitHub Wiki

Home > Long Extensions

Requirements

Make the LongExtensions library available for use:

using SaintOswald.Libraries.Extensions.LongExtensions;

Extensions


ToFileSize(bytes, decimals)

Converts the specified byte value to human readable file size format

Name Description
bytes System.Int64
The byte value to convert
decimals System.Int32
The number of decimal places in the formatted value

Returns

The specified byte value formatted as a human readable file size string

Exceptions

System.ArgumentOutOfRangeException: Thrown when the specified decimals value is less than 1 or greater than 28

Sample Usage

[TestMethod]
public void TestToFileSize()
{
    long bytes = 1099511627776;
    Assert.AreEqual("1 TB", bytes.ToFileSize());

    bytes = 1073741824;
    Assert.AreEqual("1 GB", bytes.ToFileSize());

    bytes = 1048576;
    Assert.AreEqual("1 MB", bytes.ToFileSize());

    bytes = 1024;
    Assert.AreEqual("1 KB", bytes.ToFileSize());

    bytes = 1;
    Assert.AreEqual("1 byte", bytes.ToFileSize());

    bytes = 0;
    Assert.AreEqual("0 bytes", bytes.ToFileSize());
}
[TestMethod]
public void TestToFileSizeSpecifyDecimals()
{
    long bytes = 1723914605487;
    Assert.AreEqual("1.5678912 TB", bytes.ToFileSize(7));

    bytes = 1444000217;
    Assert.AreEqual("1.34483 GB", bytes.ToFileSize(5));

    bytes = 1967128;
    Assert.AreEqual("1.876 MB", bytes.ToFileSize(3));

    bytes = 1351;
    Assert.AreEqual("1.3 KB", bytes.ToFileSize(1));
}

⚠️ **GitHub.com Fallback** ⚠️