Bytes (1024) for string conversion (1 KB)?

I would like to know if there is a function in .NET that converts numeric bytes to a string with the correct dimension?

Or do we just need to follow the old approach of separating and retaining conversion units to do this?

+5
source share
1 answer

No no.

You can write the following:

public static string ToSizeString(this double bytes) {
    var culture = CultureInfo.CurrentUICulture;
    const string format = "#,0.0";

    if (bytes < 1024)
        return bytes.ToString("#,0", culture);
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " KB";
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " MB";
    bytes /= 1024;
    if (bytes < 1024)
        return bytes.ToString(format, culture) + " GB";
    bytes /= 1024;
    return bytes.ToString(format, culture) + " TB";
}
+7
source

All Articles