Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bytes (1024) to string conversion (1 KB)?

Tags:

c#

.net

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?

like image 392
Anil Namde Avatar asked Jun 04 '10 14:06

Anil Namde


1 Answers

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";
}
like image 158
SLaks Avatar answered Sep 27 '22 21:09

SLaks