Search code examples
c#.netvb.netfilesizehuman-readable

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


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


Solution

  • This may not the most efficient or optimized 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]);