sebnilsson.com | Liquid Development Is What I Do
Seb Nilsson

Create Human-Readable File Size Strings in C#

After needing functionality in C# for getting a human-readable file-size string I posted a question about it on Stackoverflow, as one does.

The accepted answer had about 72 lines of code. One explanation for this could be that I did specify that I wanted the solution to implement IFormatProvider. Not sure why I did that, probably seemed right at the time, in the end of 2008.

One creative solution was to use a Win32 API call to StrFormatByteSizeA

[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
    public static extern long StrFormatByteSize(long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize);

Compact, clean, cross-platform solution

For the sake of simplicity, readability and the bonus of cross-platform I re-implemented an earlier solution I found, that was written in JavaScript. But the solution was easily translateble into C#.

public static class FileSizeHelper
{
    private static readonly string[] Units = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    private static string GetReadableFileSize(long size) // Size in bytes
    {
        int unitIndex = 0;
        while (size >= 1024)
        {
            size /= 1024;
            ++unitIndex;
        }

        string unit = Units[unitIndex];
        return string.Format("{0:0.#} {1}", size, unit);
    }
}