How to convert a byte size to string in C#
By FoxLearn 1/10/2025 3:03:36 AM 210
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 use JsonConverterFactory in C#
- How to serialize non-public properties using System.Text.Json
- The JSON value could not be converted to System.DateTime
- Try/finally with no catch block in C#
- Parsing a DateTime from a string in C#
- Async/Await with a Func delegate in C#
- How to batch read with Threading.ChannelReader in C#
- How to ignore JSON deserialization errors in C#