天天看點

Get the directory size

Method #1:

private static long GetDirectorySize(string directory)
        {
            var type = Type.GetTypeFromProgID("Scripting.FileSystemObject");
            var instance = Activator.CreateInstance(type);
            var folder = type.InvokeMember("GetFolder", BindingFlags.InvokeMethod, null, instance, new object[] { directory });

            long size;
            try
            {
                size = Convert.ToInt64(type.InvokeMember("Size", BindingFlags.GetProperty, null, folder, null));
            }
            catch (IOException)
            {
                throw new Exception("Insufficient Disk Space.");
            }

            Marshal.ReleaseComObject(instance);

            return size;
        }
           

Method #2

private static long GetDirectorySize(string folderPath)
        {
            DirectoryInfo di = new DirectoryInfo(folderPath);
            return di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
        }