發布時間:2020-08-06 15:32 作者:獨孤劍 閱讀:2706
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"); } } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞