C# 文件 文件夹

时间:2023-08-20 17:16:24
        //判断文件夹(路径)是否存在
if (Directory.Exists(Path))
{ } //获取文件大小
FileInfo file = new FileInfo(labOfPath);
size += file.Length; /// <summary>
/// 计算文件大小函数(保留两位小数),Size为字节大小
/// </summary>
/// <param name="Size">初始文件大小</param>
/// <returns></returns>
private static string CountSize(long Size)
{
string m_strSize = "";
long FactSize = ;
FactSize = Size;
if (FactSize < 1024.00)
m_strSize = FactSize.ToString("F2") + " Byte";
else if (FactSize >= 1024.00 && FactSize < )
m_strSize = (FactSize / 1024.00).ToString("F2") + " K";
else if (FactSize >= && FactSize < )
m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " M";
else if (FactSize >= )
m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " G";
return m_strSize;
}
        /// <summary>
/// 递归获取文件夹的大小(字节)(包含里面的子文件及子文件夹)
/// </summary>
/// <param name="size"></param>
/// <param name="Path"></param>
/// <returns></returns>
private static long GetDirectorySize(string Path)
{
long size = ;
DirectoryInfo di = new DirectoryInfo(Path);
foreach (FileInfo fi in di.GetFiles())
{
size += fi.Length;
}
DirectoryInfo[] dis = di.GetDirectories();
if (dis.Length > )
{
for (int i = ; i < dis.Length; i++)
{
size += GetDirectorySize(dis[i].FullName);
}
}
return size;
}