tags:

views:

118

answers:

3

I'm converting an old app that records folder sizes on a daily basis. The legacy app uses the Scripting.FileSystemObject library:

Set fso = CreateObject("Scripting.FileSystemObject")
Set folderObject = fso.GetFolder(folder)
size = folderObject.Size

There isn't an equivalent mechanism on the System.IO.Directory and System.IO.DirectoryInfo classes.

To achieve the same result in .NET do I actually have to recursively walk the whole folder structure keeping a running total of file sizes?

Update: @Jonathon/Ed - thanks....as I thought. I think I'll just reference the Scripting.FileSystemObject COM library. Works just as well even if breaking the .NET purity of my app. It's for an internal reporting app so it's not such a big deal.

Thanks
Kev

+3  A: 

Sadly, yes...who knows why.

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);  
}

As seen at:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

FlySwat
+2  A: 

I think that you already know the answer; you will need to add up all of the files in the directory (as well as its child directories.) I don't know of any built in function for this, but hey, I don't know everything (not even close).

Ed Swangren
A: 

Mads Kristensen posted about this a while back:

http://blog.madskristensen.dk/post/Calculate-the-total-size-of-a-directory-in-C.aspx

Josh Stodola