Rozmiar pliku czytelny dla użytkownika

Potrzebowałem funkcję do konwertowania długości pliku w bajtach na zjadliwą dla użytkownika formę. Zgodnie z tdd najpierw należy napisać test:

[Test]
[Row(1, „1 B”)]
[Row(1024, „1 KB”)]
[Row(2000, „1,95 KB”)]
[Row(1048576, „1 MB”)]
[Row(1537500, „1,47 MB”)]
[Row(5242880, „5 MB”)]
[Row(1073741824, „1 GB”)]
public void ToFileSize_Tests(int value, string expected)
{
var fileSize = value.ToFileSize();
Assert.AreEqual(expected, fileSize);
}

 

a potem wygooglować odpowiedni kod. Znalazłem taki, który urzekł mnie prostotą i elegancją.

string[] sizes = { "B", "KB", "MB", "GB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order + 1 < sizes.Length) {
    order++;
    len = len/1024;
}

// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
string result = String.Format("{0:0.##} {1}", len, sizes[order]);

Źródło: http://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size-in-bytes-abbreviation-using-net