private long RecurseDirectory(string directory, int level, out int files, out int folders)
{
IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
long size = 0;
files = 0;
folders = 0;
WIN32_FIND_DATA findData;
//IntPtr findHandle;
// please note that the following line won't work if you try this on a network folder, like \\Machine\C$
// simply remove the \\?\ part in this case or use \\?\UNC\ prefix
IntPtr findHandle = FindFirstFile($@"\\?\{directory}\*", out findData);
if (findHandle != INVALID_HANDLE_VALUE)
{
do
{
if (bgw.CancellationPending)
break;
if ((findData.dwFileAttributes & System.IO.FileAttributes.Directory) != 0)
{
if (findData.cFileName != "." && findData.cFileName != "..")
{
folders++;
int subfiles, subfolders;
string subdirectory = directory + (directory.EndsWith(@"\") ? "" : @"\") +
findData.cFileName;
if (level != 0)
{ // allows -1 to do complete search.
size += RecurseDirectory(subdirectory, level - 1, out subfiles, out subfolders);
folders += subfolders;
files += subfiles;
}
}
}
else
{
// File
files++;
size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296;
}
}
while (FindNextFile(findHandle, out findData));
FindClose(findHandle);
}
return size;
}