How to convert a byte size to string in C#
By FoxLearn 1/10/2025 3:03:36 AM 136
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#