C# 统计文件字节存储长度,转换为B,KB,GB,TB函数
|
admin
2025年7月14日 22:34
本文热度 976
|
统计文件字节存储长度(即文件大小),可用于存储空间管理,特别是目前云存储计费按实际存储字节数收费,如何将字节转换为B,KB,GB,TB方式表示,方法如下:
(1)获取文件长度:
public int GetFileLength(string filePath){ FileInfo fi = new FileInfo(filePath);
return (int)fi.Length;}
(2)转换为B,KB,GB,TB方式表示
public string GetFileSize(double FileLength){ string Result = ""; try { if (FileLength >= 1024 * 1024 * 1024) { if (FileLength / 1024 / 1024 / 1024 >= 1024) Result = string.Format("{0:########0.##} T", (double)FileLength / 1024 / 1024 / 1024); else Result = string.Format("{0:####0.##} G", (double)FileLength / 1024 / 1024 / 1024); } else if (FileLength >= 1024 * 1024) Result = string.Format("{0:####0.##} M", (double)FileLength / 1024 / 1024); else if (FileLength >= 1024) Result = string.Format("{0:####0.##} K", (double)FileLength / 1024); else if (FileLength > 0) Result = string.Format("{0:####0.##} K", FileLength / 1024); else Result = "0 M"; } catch (Exception ex) { return ex.Message; } return Result;}
阅读原文:原文链接
该文章在 2025/7/15 10:45:15 编辑过