How to convert a byte size to string in C#

By FoxLearn 1/10/2025 3:03:36 AM   61
When dealing with byte sizes in C#, you often need to present the size in a more understandable format, such as KB, MB, GB, or TB.

There are many ways to achieve this, but here’s a simple and readable solution implemented as an extension method.

public static class LongExtensions
{
    public static string ToSizeString(this long bytes)
    {
        // Define units and corresponding thresholds
        string[] sizeUnits = { "Bytes", "KB", "MB", "GB", "TB" };
        long[] sizeThresholds = { 1, 1024, 1024 * 1024, 1024 * 1024 * 1024, 1024 * 1024 * 1024 * 1024 };

        // Find the index of the appropriate unit by dividing bytes by the size threshold
        int index = 0;
        double size = bytes;

        while (index < sizeThresholds.Length - 1 && size >= sizeThresholds[index + 1])
        {
            size /= 1024;
            index++;
        }

        // Round to 2 decimal places and return the result
        return $"{Math.Round(size, 2)} {sizeUnits[index]}";
    }
}

This code defines an extension method ToSizeString for the long data type.

  • We use two arrays sizeUnits for the units (Bytes, KB, MB, etc.) and sizeThresholds for their corresponding byte size thresholds.

  • We use a while loop to iterate through the size thresholds, progressively dividing the byte value by 1024 until we find the correct unit.

You can use this extension method simply by calling it on a long variable:

public static void Main()
{
    long bytes = 42069;
    Console.WriteLine(bytes.ToSizeString()); // 41.08 KB
}

This method will convert the byte value into the appropriate unit (KB, MB, GB, etc.), making it easier to read and understand.