C# 快速計算資料夾容量 C# 快速計算資料夾容量
  .NET       ez      2014-10-06

以往計算資料夾容量,需要使用迴圈計算檔案容量,然後在加起來,例如:

        private static void CalculateDirectorySize(string DirRoute, ref long totalSize)
        {
            foreach (string Route in Directory.EnumerateDirectories(DirRoute)) CalculateDirectorySize(Route, ref totalSize);
            foreach (FileInfo file in new DirectoryInfo(DirRoute).EnumerateFiles()) totalSize += file.Length;
        }

雖然可以計算,不過效率不太好,改用內建的 Scripting.FileSystemObject,速度會快上許多:

        private static long CalculateDirectorySize(string DirRoute)
        {
            try
            {
                Type tp = Type.GetTypeFromProgID("Scripting.FileSystemObject");
                object fso = Activator.CreateInstance(tp);
                object fd = tp.InvokeMember("GetFolder", BindingFlags.InvokeMethod, null, fso, new object[] { DirRoute });
                long ret = Convert.ToInt64(tp.InvokeMember("Size", BindingFlags.GetProperty, null, fd, null));
                Marshal.ReleaseComObject(fso);
                return ret;
            }
            catch
            {
                return 0;
            }
        }

標籤:   .NET

我要留言