5

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

Or we just need to follow old approach of dividing and holding the conversion units to get it done?

Anil Namde
  • 6,452
  • 11
  • 63
  • 100

1 Answers1

7

No, there isn't.

You can write one like this:

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";
}
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Unless I'm mistaken, I think it would have been better to iterate with a `while` or `do` loop. And that solution would be better on the eyes as well. That's just my opinion. :\ – Alex Essilfie Mar 11 '11 at 09:46
  • @Alex: You're right; I hadn't thought of that. I later saw a different answer that did so. – SLaks Mar 11 '11 at 13:19