冰楓論壇
標題:
[C#] 計算資料夾容量
[打印本頁]
作者:
whitefox
時間:
2023-6-2 11:28
標題:
[C#] 計算資料夾容量
一般計算一個資料夾容量大小用遞迴方式累加各個檔案容量大小
public static void CalculateDirectorySize(string DirPath, ref long TotalSize)
{
foreach (string p in Directory.EnumerateDirectories(DirPath))
{
CalculateDirectorySize(p, ref totalSize);
}
foreach (FileInfo fi in new DirectoryInfo(DirPath).EnumerateFiles())
{
TotalSize += fi.Length;
}
}
複製代碼
還有另一個選擇使用Scripting.FileSystemObject,執行效率更高
public static long CalculateDirectorySize(string DirPath)
{
try
{
Type tp = Type.GetTypeFromProgID("Scripting.FileSystemObject");
object fso = Activator.CreateInstance(tp);
object fd = tp.InvokeMember("GetFolder", BindingFlags.InvokeMethod, null, fso, new object[] { DirPath });
long ret = Convert.ToInt64(tp.InvokeMember("Size", BindingFlags.GetProperty, null, fd, null));
Marshal.ReleaseComObject(fso);
return ret;
}
catch
{
return 0;
}
}
複製代碼
歡迎光臨 冰楓論壇 (https://bingfong.com/)
Powered by 冰楓