代码片段-计算文件字节大小,以合适的单位显示

 1     /// <summary>
 2     /// 返回文件体积大小描述
 3     /// </summary>
 4     /// <param name="bytesCount">字节数量</param>
 5     /// <returns></returns>
 6     private string Calc(long bytesCount)
 7     {
 8       var units = new[] { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", "BB" };
 9 
10       int index = 0;
11       double k = bytesCount;
12 
13       if (bytesCount >= 1024)
14       {
15         while (true)
16         {
17           k = k / 1024;
18 
19           index++;
20           if (k < 1024) break;
21         }
22       }
23 
24       return $"{k:f2}{units[index]}";
25     }
26   }

 

posted @ 2019-05-15 10:20  X-Cracker  阅读(488)  评论(0编辑  收藏  举报