我如何获得以字节为单位缩写使用.NET人类可读的文件大小是多少?文件大小、缩写、字节、如何获得

2023-09-02 01:22:53 作者:时光帯走忧伤

我要如何以字节为单位的缩写一个人类可读的文件大小使用.NET?

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

示例: 以输入7326629,并显示6.98 MB

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

推荐答案

这是不是最有效的方式来做到这一点,但它更容易,如果你不熟悉的日志数学阅读,应该足够快,大多数情况

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" };
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]);
 
精彩推荐
图片推荐