文件大小帮助类
public class SizeHelper
{
/// <summary>
/// 获取文件大小并以B,KB,GB,TB方式表示
/// </summary>
/// <param name="file">文件(FileInfo类型)</param>
/// <returns></returns>
public static string GetFileSize(FileInfo file)
{
string result = "";
long length = file.Length;
bool flag = length >= 1073741824L;
if (flag)
{
result = ((length / 1024L * 1024L * 1024L * 1024L >= 1024L) ? string.Format("{0:############0.00} TB", (double)length / 1024.0 * 1024.0 * 1024.0 * 1024.0) : string.Format("{0:####0.00} GB", (double)length / 1024.0 * 1024.0 * 1024.0));
}
else
{
bool flag2 = length >= 1048576L;
if (flag2)
{
result = string.Format("{0:####0.00} MB", (double)length / 1024.0 * 1024.0);
}
else
{
bool flag3 = length >= 1024L;
if (flag3)
{
result = string.Format("{0:####0.00} KB", (double)length / 1024.0);
}
else
{
result = string.Format("{0:####0.00} Bytes", length);
}
}
}
return result;
}
/// <summary>
/// 获取文件大小并以B,KB,GB,TB方式表示
/// </summary>
/// <param name="filePath">文件的具体路径</param>
/// <returns></returns>
public static string GetFileSize(string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
long length = fileInfo.Length;
bool flag = length >= 1073741824L;
string result;
if (flag)
{
result = ((length / 1024L * 1024L * 1024L * 1024L >= 1024L) ? string.Format("{0:########0.00} TB", (double)length / 1024.0 * 1024.0 * 1024.0 * 1024.0) : string.Format("{0:####0.00} GB", (double)length / 1024.0 * 1024.0 * 1024.0));
}
else
{
bool flag2 = length >= 1048576L;
if (flag2)
{
result = string.Format("{0:####0.00} MB", (double)length / 1024.0 * 1024.0);
}
else
{
bool flag3 = length >= 1024L;
if (flag3)
{
result = string.Format("{0:####0.00} KB", (double)length / 1024.0);
}
else
{
result = string.Format("{0:####0.00} Bytes", length);
}
}
}
return result;
}
/// <summary>
/// 计算文件大小函数(保留两位小数),Size为字节大小
/// </summary>
/// <param name="size">初始文件大小</param>
/// <returns></returns>
public static string CountSize(long size)
{
string result = "";
long num = size;
bool flag = (double)num < 1024.0;
if (flag)
{
result = num.ToString("F2") + " 字节";
}
else
{
bool flag2 = (double)num >= 1024.0 && num < 1048576L;
if (flag2)
{
double num2 = (double)num / 1024.0;
result = num2.ToString("F2") + " KB";
}
else
{
bool flag3 = num >= 1048576L && num < 1073741824L;
if (flag3)
{
double num2 = (double)num / 1024.0 / 1024.0;
result = num2.ToString("F2") + " MB";
}
else
{
bool flag4 = num >= 1073741824L;
if (flag4)
{
double num2 = (double)num / 1024.0 / 1024.0 / 1024.0;
result = num2.ToString("F2") + " GB";
}
}
}
}
return result;
}
}
本文来自博客园,作者:码农阿亮,转载请注明原文链接:https://www.cnblogs.com/wml-it/p/16522502.html
技术的发展日新月异,随着时间推移,无法保证本博客所有内容的正确性。如有误导,请大家见谅,欢迎评论区指正!
开源库地址,欢迎点亮:
GitHub:https://github.com/ITMingliang
Gitee: https://gitee.com/mingliang_it
GitLab: https://gitlab.com/ITMingliang
建群声明: 本着技术在于分享,方便大家交流学习的初心,特此建立【编程内功修炼交流群】,为大家答疑解惑。热烈欢迎各位爱交流学习的程序员进群,也希望进群的大佬能不吝分享自己遇到的技术问题和学习心得!进群方式:扫码关注公众号,后台回复【进群】。