[C#][Extension Method]Get directory size
namespace ConsoleApplication8 { class Program { static void Main(string[] args) { GetFolderSize(@“C:\Program Files”); GetDirSize(@“C:\Program Files”); DirSize(new DirectoryInfo(@“C:\Program Files”));
var sw = Stopwatch.StartNew();
Console.WriteLine(GetFolderSize(@"C:\Program Files"));
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Stop();
sw.Reset();
sw.Start();
Console.WriteLine(GetDirSize(@"C:\Program Files"));
Console.WriteLine(sw.ElapsedMilliseconds);
sw.Stop();
sw.Reset();
sw.Start();
Console.WriteLine(DirSize(new DirectoryInfo(@"C:\Program Files")));
Console.WriteLine(sw.ElapsedMilliseconds);
}
static long GetDirSize(string path)
{
return (from item in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories)
select new FileInfo(item).Length).Sum();
}
static long GetFolderSize(string folder) // 取得資料夾大小
{
return long.Parse((new Scripting.FileSystemObjectClass()).GetFolder(folder).Size.ToString());
}
public static long DirSize(DirectoryInfo d)
{
long Size = 0;
// Add file sizes.
FileInfo[] fis = d.GetFiles();
foreach (FileInfo fi in fis)
{
Size += fi.Length;
}
// Add subdirectory sizes.
DirectoryInfo[] dis = d.GetDirectories();
foreach (DirectoryInfo di in dis)
{
Size += DirSize(di);
}
return (Size);
}
}
}
public static class DirectoryInfoExtension { public static long GetSize(this DirectoryInfo dirInfo) { Type tp = Type.GetTypeFromProgID(“Scripting.FileSystemObject”); object fso = Activator.CreateInstance(tp); object fd = tp.InvokeMember(“GetFolder”, BindingFlags.InvokeMethod, null, fso, new object[] { dirInfo.FullName }); long ret = Convert.ToInt64(tp.InvokeMember(“Size”, BindingFlags.GetProperty, null, fd, null)); Marshal.ReleaseComObject(fso); return ret; } }