How to convert a byte size to string in C#
By FoxLearn 1/10/2025 3:03:36 AM 61
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.) andsizeThresholds
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.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#