8

Possible Duplicate:
How do I get a directory size (files in the directory) in C#?

In vbscript, it's incredibly simple to get the folder size in GB or MB:

Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim fSize = CInt((oFSO.GetFolder(path).Size / 1024) / 1024)
WScript.Echo fSize

In C#, with all my searches, all I can come up with are long, convoluted, recursive searches for every file size in all subfolders, then add them all up at the end.

Is there no other way?

Community
  • 1
  • 1
Nathan McKaskle
  • 2,926
  • 12
  • 55
  • 93
  • VBScript and C# run on different environments, you know. Maybe the easiest way is to run a VBScript from your app. Check this out: http://stackoverflow.com/questions/200422/how-to-call-a-vbscript-file-in-a-c-sharp-application – Andre Calil Aug 28 '12 at 19:44
  • @AndreCalil: No; that is not the easiest way. – SLaks Aug 28 '12 at 19:45
  • @SLaks Could you point what would be an easier way? I don't know of any builtin solution besides the sum of the files. – Andre Calil Aug 28 '12 at 19:47

2 Answers2

28

How about this:

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

from here.

This will give you the size in bytes; you will have to "prettify" that into GBs or MBs.

NOTE: This only works in .NET 4+.

EDIT: Changed the wildcard search from "*.*" to "*" as per the comments in the thread to which I linked. This should extend its usability to other OSes (if using Mono, for example).

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
4

You can also use recursion to get all subdirectories and sum the sizes:

public static long GetDirectorySize(string path){
    string[] files = Directory.GetFiles(path);
    string[] subdirectories = Directory.GetDirectories(path);

    long size = files.Sum(x => new FileInfo(x).Length);
    foreach(string s in subdirectories)  
        size += GetDirectorySize(s);

    return size;
}
Omar
  • 16,329
  • 10
  • 48
  • 66
  • 1
    Correct but *"In C#, with all my searches, all I can come up with are long, convoluted, recursive searches for every file size in all subfolders, then add them all up at the end."* – L.B Aug 28 '12 at 20:29