C# Folder Size, Or Maybe I Am Ignorant

I apologize for the lack of posting recently – since it is Fall registration we are in a freeze which means no changes to anything until it’s over.  Always a good time to research something that I might need later.  I’ve been paging through Advanced Windows Debugging but I’m not enough of a programmer to understand everything.

Additionally, my site was under some sort of attack which ended up with my host disabling the log-in page for WordPress.  Good for them, I was glad they did.  Not sure what caused that, but you can be assured none of your personal information was stolen, since I don’t keep any, and the system wasn’t compromised anyway.

In any case, I was looking at a question on Reddit concerning PowerShell and getting folder size, create, and modify times from a script.  Problem being, the pathing could be more than 260 characters.  If you’ve never run in to the problem, here is the background.  While the poster did finally manage to get the file size using robocopy, I suggested he use .Net to get creation and modified dates.  This is fairly straightforward:

$CreateTime = [System.IO.File]::GetCreationTime($i)
$LastModified = [System.IO.File]::GetLastWriteTime($i)

where $i is the file or folder name.

But then I got to thinking – surely there must be a better way than robocopy to get file sizes for long paths?  Let’s take a look at .Net for this too…

Since GetCreationTime and GetLastWriteTime seem to work on folders as well despite the library being named “File”, I thought the following code would work too:

$files = [System.IO.Directory]::GetFiles($i)
foreach ($file in $files)
{
$size += $file.Length;
}

But, for some reason, this will only get the size of the files inside the directory, which doesn’t include any folders that might be under it.  You actually need to iterate through the whole source directory to get everything that might be there in order to get the total size.  It appears that this is a limitation of the Windows API.

Now, that being said, I am not a C# developer by any means, so there might be an easy way to do this that I don’t know.  It’s just that it seems inconsistent to me given the naming conventions between the two libraries.  I can get folder modified times and creation times using a File call, but not the sizes of a root folder.  Why?

If Get-ChildItem could lose its 260 character limitation that would probably help out a lot.  I suppose you could use PSDrives to shrink the path, but sometimes that wouldn’t be an option given the structure of a file system.