private static long CalculateFolderSize(string path, out int files, out int folders) { files = 0; folders = 0; IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); long size = 0; FindData findData = new FindData(); IntPtr findHandle; findHandle = path.StartsWith("\\\\") ? Kernel32.FindFirstFile(path + @"\*", findData) : Kernel32.FindFirstFile(@"\\?\" + path + @"\*", findData); if (findHandle != INVALID_HANDLE_VALUE) { do { if ((findData.fileAttributes & (int)FileAttributes.Directory) != 0) { if (findData.fileName != "." && findData.fileName != "..") { folders++; int subfiles, subfolders; string subdirectory = path + (path.EndsWith(@"\") ? "" : @"\") + findData.fileName; size += CalculateFolderSize(subdirectory, out subfiles, out subfolders); folders += subfolders; files += subfiles; } } else { // File files++; size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296; } }while (Kernel32.FindNextFile(findHandle, findData)); Kernel32.FindClose(findHandle); } return(size); }
public static extern IntPtr FindFirstFile(String fileName, [In, Out] FindData findFileData);
public static extern bool FindNextFile(IntPtr hFindFile, [In, Out] FindData lpFindFileData);
private static long CalculateFolderSize(string path, out int files, out int folders) { files = 0; folders = 0; IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); long size = 0; FindData findData = new FindData(); IntPtr findHandle; findHandle = path.StartsWith("\\\\") ? Kernel32.FindFirstFile(path + @"\*", findData) : Kernel32.FindFirstFile(@"\\?\" + path + @"\*", findData); if (findHandle != INVALID_HANDLE_VALUE) { do { if ((findData.fileAttributes & (int)FileAttributes.Directory) != 0) { if (findData.fileName != "." && findData.fileName != "..") { folders++; int subfiles, subfolders; string subdirectory = path + (path.EndsWith(@"\") ? "" : @"\") + findData.fileName; size += CalculateFolderSize(subdirectory, out subfiles, out subfolders); folders += subfolders; files += subfiles; } } else { // File files++; size += (long)findData.nFileSizeLow + (long)findData.nFileSizeHigh * 4294967296; } } while (Kernel32.FindNextFile(findHandle, findData)); Kernel32.FindClose(findHandle); } return size; }