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");
            }
        }
    }
}


作者最新文章
Winform TextBox (文本框) 密码输入框, 输入内容显示*号 (星号)
Winform 启动前弹出登录界面, 登录成功之后再显示主界面
C# 字符串string和字符数组char[]的相互转换
C# 字符串倒序输出, 实现字符串倒序的方法
Winform 如何从 TextBox(文本框) 控件读取每一行数据到数组