This is the second version of my previous directory size utility. If you haven't seen it, you can take a look here. Although it is the second version, it uses an older version of the .NET Framework - version 2.0. It improves on the first version in that it can ignore inaccessible files and directories without skipping everything that follows the inaccessible file or directory.
This utility is written in Visual Studio 2013 Express, and you'll need to enable or install .NET Framework 2.0 if it is not already present. For details on how to do this, go here (Windows XP) or here (Windows 8), depending on your OS.
Recursively Listing Files
Unlike the previous version, we manually recurse over subdirectories to get each one's size. An inaccessible directory will throw an
UnauthorizedAccessException in the recursive method. You may note that I've caught the generic
Exception, but that's just me being lazy, modify it to your liking. Here's the function that does all the work. It calls itself recursively whenever it encounters a subdirectory.
static UInt64 GetFilesInDirectory(string directory, ref bool errors)
UInt64 size = 0;
DirectoryInfo di = new DirectoryInfo(directory); try
DirectoryInfo directories = di.GetDirectories("*", SearchOption.TopDirectoryOnly);
if (directories != null)
foreach (DirectoryInfo dir in directories)
size += GetFilesInDirectory(dir.FullName, ref errors);
FileInfo files = di.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (FileInfo file in files)
size += (UInt64)file.Length;
catch (Exception ex)
errors = true;
To explain it simply, the method takes two arguments; the first specifies which directory to scan, and the second returns a flag indicating whether there were any errors accessing subdirectories. It calls
DirectoryInfo.GetDirectories internally to get all subdirectories, calling itself recursively on each of these. It then calls
DirectoryInfo.GetFiles and sums the sizes of all the files in the specified directory, adding them to the size returned by the recursive call.
This version returns a more accurate size in case of errors. The previous .NET 4 version aborts all files and subdirectories following an access denial exception, but this one only fails on the inaccessible subdirectory.
I have hardcoded the error message mechanism to show a single message in case of one or more access denials. You may modify the code as indicated in the comments to print a message per error. Future versions will include command line options to switch this behavior.
Bug reports and comments are welcome. I've only tested this on one OS, so your mileage may vary. Keep me posted.