public static class TxxTool
{
#region 读取文件大小
private static List<string> DirList = new List<string>();
public static long GetFileSize(string path)
{
DirList = new List<string>();
DirList.Add(path);
GetAllDirecotries(path);
long fileSize = 0;
foreach (var itemPath in DirList)
{
fileSize += GetDirectoriesSize(itemPath);
}
return fileSize;
}
private static void GetAllDirecotries(string dirPath)
{
if (Directory.Exists(dirPath) == false)
{
return;
}
DirectoryInfo[] dirArray = new DirectoryInfo(dirPath).GetDirectories();
foreach (DirectoryInfo item in dirArray)
{
DirList.Add(item.FullName);
GetAllDirecotries(item.FullName);
}
}
private static long GetDirectoriesSize(string dirPath)
{
if (Directory.Exists(dirPath) == false)
{
return 0;
}
long size = 0;
DirectoryInfo dir = new DirectoryInfo(dirPath);
foreach (FileInfo info in dir.GetFiles())
{
size += info.Length;
}
DirectoryInfo[] dirBotton = dir.GetDirectories();
foreach (DirectoryInfo info in dirBotton)
{
size += GetDirectoriesSize(info.FullName);
}
return size;
}
public static string GetFormatSizeString(int size)
{
string[] ns = new string[] { "Byte", "KB", "MB", "GB", "TB", "PB" };
double baseNum = 1024;
if (size <= 0)
{
return $"{0.ToString("F2")} {ns[0]}";
}
int pow = Math.Min((int)Math.Floor(Math.Log(size, baseNum)), ns.Length - 1);
return $"{(size / Math.Pow(baseNum, pow)).ToString("F2")} {ns[pow]}";
}
#endregion
}