2010-06-04 16 views
5

Me gustaría saber si hay una función en .NET que convierta bytes numéricos en la cadena con la medición correcta?bytes (1024) a la conversión de cadenas (1 KB)?

¿O simplemente tenemos que seguir el viejo enfoque de dividir y mantener las unidades de conversión para que se haga?

+0

Tome un vistazo @ http://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size -using-net –

+0

wow parece que esta publicación realmente tiene diferentes sabores :) Gracias hombre –

Respuesta

7

No, no lo hay.

Puede escribir uno como este:

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"; 
} 
+0

A menos que me equivoque, creo que hubiera sido mejor iterar con un ciclo 'while' o' do'. Y esa solución también sería mejor para los ojos. Esa es solo mi opinión. : \ –

+0

@Alex: tienes razón; No había pensado en eso. Más tarde vi una respuesta diferente que lo hizo. – SLaks

+0

Ganked [.] (Http://stealinurcode.lol) – Will

Cuestiones relacionadas