学无先后达者为师!
不忘初心,砥砺前行。

使用 C# 获取文件或流的易读大小(KB、MB、GB、TB、KB)

无论是 FileInfo 还是 Stream ,Length 属性代表的是文件或流的大小,单位是 Byte ,该数值非常精确,但并不易读。为此,笔者编辑整理了以下代码用于将 Byte 长度转换为易于阅读的格式。支持 B、KB、MB、GB、TB和PB 单位。

private static readonly string[] suffixes = new string[] { " B", " KB", " MB", " GB", " TB", " PB" };
/// 
/// 获取文件大小的显示字符串
/// 
/// 
/// 
public static string BytesToReadableValue(long number)
{
    double last = 1;
    for (int i = 0; i < suffixes.Length; i++)
    {
        var current = Math.Pow(1024, i + 1);
        var temp = number / current;
        if (temp < 1)
        {
            return (number / last).ToString("n2") + suffixes[i];
        }
        last = current;
    }
    return number.ToString();
}

使用方式如下:

static void Main()
{
    using (var fs = File.OpenRead(@"D:\be28e70d.iso"))
    {
        var len = fs.Length;
        Console.WriteLine(BytesToReadableValue(len));
    }
}

这将会输出: 5.64 GB

赞(3) 打赏
未经允许不得转载:码农很忙 » 使用 C# 获取文件或流的易读大小(KB、MB、GB、TB、KB)

评论 2

  1. 学到了,谢谢大佬。

    Soar、毅5年前 (2021-06-23)
  2. #1

    /// <summary>
    /// 转换为容易阅读的字节计数
    /// </summary>
    /// <param name="bytes"></param>
    /// <param name="si"></param>
    /// <returns></returns>
    public static string humanReadableByteCount(long bytes, bool si = false)
    {
    int unit = si ? 1000 : 1024;
    if (bytes < unit) return bytes + " B";
    int exp = (int)(Math.Log(bytes) / Math.Log(unit));
    string pre = (si ? "kMGTPE" : "KMGTPE")[exp – 1] + (si ? "" : "i");
    return string.Format("{0:F1} {1}B", bytes / Math.Pow(unit, exp), pre);
    }

    xlog5年前 (2021-06-23)

给作者买杯咖啡

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册