本文将使用 C# 8.0 写一个相对比较省内存和性能不差的将文件长度从 Bytes 转换为单位使用 KB 或 MB 或 GB 等单位的字符串的方法
代码可以复制在你的实际软件中使用
static class FileSizeFormatter { public static string FormatSize(long bytes, string formatString = "{0:0.00}") { int counter = 0; double number = bytes;
// 最大单位就是 PB 了,而 PB 是第 5 级,从 0 开始数 // "Bytes", "KB", "MB", "GB", "TB", "PB" const int maxCount = 5;
while (Math.Round(number / 1024) >= 1) { number = number / 1024; counter++;
if (counter >= maxCount) { break; } }
var suffix = counter switch { 0 => "B", 1 => "KB", 2 => "MB", 3 => "GB", 4 => "TB", 5 => "PB", // 通过 maxCount 限制了最大的值就是 5 了 _ => throw new ArgumentException("骚年,你是不是忘了更新 maxCount 等级了") };
return $"{string.Format(formatString, number)}{suffix}"; } }
上面代码使用的 switch 根据 counter 返回对应的单位,对比使用数组的优势在于不需要创建数组对象,能省一点内存。同时进行的计算也比较少,相对性能也不差
上面代码的 ArgumentException 在没有更改代码逻辑是不会进入的,因为通过 maxCount 限制了单位最大就是 PB 了
试试以下测试代码
for (int i = 0; i < 10; i++) { Debug.WriteLine(FileSizeFormatter.FormatSize((long)Math.Pow(10, i))); }
可以看到控制台的输出如下
1.00B10.00Bytes100.00Bytes0.98KB9.77KB97.66KB0.95MB9.54MB95.37MB0.93GB
其他小伙伴的实现如下
c# 字节单位转换_weixin_34405925的博客-CSDN博客_c# 单位转换
C#实现获取文件大小进行单位转换与文件大小比较_xiaochenXIHUA的博客-CSDN博客_c# 文件大小单位
也有更快计算当前的数值对应的单位的等级的方法,就是通过 Math.Log 的方法,我没有测试性能对比,但是看起来相差很小,因为循环也就是最多 5 次
var mag = (int)Math.Max(0, Math.Log(value, 1024)); var adjustedSize = Math.Round(value / Math.Pow(1024, mag), decimalPlaces);
当然,也有更快的方法,就是通过判断大小
private string GetFileSize(double byteCount) { string size = "0 B"; if (byteCount >= 1073741824.0) size = string.Format("{0:##.##}", byteCount / 1073741824.0) + " GB"; else if (byteCount >= 1048576.0) size = string.Format("{0:##.##}", byteCount / 1048576.0) + " MB"; else if (byteCount >= 1024.0) size = string.Format("{0:##.##}", byteCount / 1024.0) + " KB"; else if (byteCount > 0 && byteCount < 1024.0) size = byteCount.ToString() + " B";
return size; }
只是判断大小的代码没有用到 C# 8.0 因此依然推荐小伙伴使用本文开始的代码

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。 欢迎转载、使用、重新发布,但务必保留文章署名 林德熙 (包含链接: https://blog.lindexi.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我 联系。