C# 转换字节大小、长度, 根据字节大小范围返回KB, MB, GB自适长度

C# 转换字节大小、长度, 根据字节大小范围返回KB, MB, GB自适长度


using System;
using System.IO;

namespace ConsoleApp19
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("1024*5 {0}", FileSizeString(1024L * 5L));// 5 KB
            Console.WriteLine("1024*1024*5 {0}", FileSizeString(1024L * 1024L * 5L));// 5 MB
            Console.WriteLine("1024*1024*1024*5 {0}", FileSizeString(1024L * 1024L * 1024L * 5L));// 5 GB
            Console.WriteLine("1024*1024*1024*1024*5 {0}", FileSizeString(1024L * 1024L * 1024L * 1024L * 5L));// 5 TB
            Console.WriteLine("1024*1024*1024*1024*1024*5 {0}", FileSizeString(1024L * 1024L * 1024L * 1024L * 1024L * 5L));// 5 PB
            Console.WriteLine("1024*1024*1024*1024*1024*1024*5 {0}", FileSizeString(1024L * 1024L * 1024L * 1024L * 1024L * 1024L * 5L));// 5 EB

            Console.Read();
        }

        /// <summary>
        /// 转换字节大小、长度, 根据字节大小范围返回KB, MB, GB自适长度
        /// </summary>
        /// <param name="length">传入字节大小</param>
        /// <returns></returns>
        public static string FileSizeString(long length)
        {
            int byteConversion = 1024;
            double bytes = Convert.ToDouble(length);

            // 超过EB的单位已经没有实际转换意义了, 太大了, 忽略不用
            if (bytes >= Math.Pow(byteConversion, 6)) // EB
            {
                return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 6), 2), " EB");
            }
            if (bytes >= Math.Pow(byteConversion, 5)) // PB
            {
                return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 5), 2), " PB");
            }
            else if (bytes >= Math.Pow(byteConversion, 4)) // TB
            {
                return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 4), 2), " TB");
            }
            else if (bytes >= Math.Pow(byteConversion, 3)) // GB
            {
                return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 3), 2), " GB");
            }
            else if (bytes >= Math.Pow(byteConversion, 2)) // MB
            {
                return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 2), 2), " MB");
            }
            else if (bytes >= byteConversion) // KB
            {
                return string.Concat(Math.Round(bytes / byteConversion, 2), " KB");
            }
            else // Bytes
            {
                return string.Concat(bytes, " Bytes");
            }
        }
    }
}

作者最新文章
C# ASP.NET 中html常见转义字符的处理
C# ASP.NET移除html标签, 过滤html标签
C# 获取文件的创建时间、访问时间、修改时间
ASP.NET Session 操作, 以用户登录退出为例, 实现Session的获取, 设置, 清除
ASP.NET Cookie 操作, 以用户登录退出为例, 实现Cookie的获取, 设置, 清除