How do I get a human-readable file size in bytes abbreviation using .NET?

Larsenal picture Larsenal · Nov 11, 2008 · Viewed 157.6k times · Source

How do I get a human-readable file size in bytes abbreviation using .NET?

Example: Take input 7,326,629 and display 6.98 MB

Answer

David Thibault picture David Thibault · Nov 11, 2008

This is not the most efficient way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.

string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
    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]);