我如何获得以字节为单位缩写使用.NET人类可读的文件大小是多少? [英] How do I get a human-readable file size in bytes abbreviation using .NET?

查看:100
本文介绍了我如何获得以字节为单位缩写使用.NET人类可读的文件大小是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要如何以字节为单位的缩写一个人类可读的文件大小使用.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]);

这篇关于我如何获得以字节为单位缩写使用.NET人类可读的文件大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆