C# 8.0 文件长度 Bytes 字节转 KB 等单位字符串

时间:2022-07-22
本文章向大家介绍C# 8.0 文件长度 Bytes 字节转 KB 等单位字符串,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文将使用 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.00B
10.00Bytes
100.00Bytes
0.98KB
9.77KB
97.66KB
0.95MB
9.54MB
95.37MB
0.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 因此依然推荐小伙伴使用本文开始的代码


本文会经常更新,请阅读原文: https://blog.lindexi.com/post/C-8.0-%E6%96%87%E4%BB%B6%E9%95%BF%E5%BA%A6-Bytes-%E5%AD%97%E8%8A%82%E8%BD%AC-KB-%E7%AD%89%E5%8D%95%E4%BD%8D%E5%AD%97%E7%AC%A6%E4%B8%B2.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。