How to get exact directory size on disk
.net, c#, filesize, pinvoke, windows
Solution
This is a neater way:-
private static long GetDirectorySize(string path)
{
DirectoryInfo dir = new DirectoryInfo(path);
return dir.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(file=> file.Length);
}
Basically, EnumerateFiles returns a list of `FileInfo`, and we are using its `Length` property to sum the total file size of the directory.
Although it still uses recursion to get directory size, but it sure is a neater way to do so.
To get the Size on disk using C#, you have to dig deeper, like using GetDiskFreeSpace
Also, check out the following msdn thread
Hope this helps!
Problem
I'm new in working with the Windows file system and I've been stuck on this problem for a few days. I'm coding with C# and what I want is to get the exact "size on disk" of a directory, like displayed in the Properties dialog of directories on Windows 7. Now I am able to get a rough figure, traversing through every file and every subdirectory in the directory, using the API `GetCompressedFileSize` in `kernel32.dll` for compressed files and the `FileInfo.Length` property rounded to a multiple of the cluster size for normal files. I found that some files share clusters (?) (size on disk not a multiple of cluster size) while others occupy clusters separately, then I can't get an exact size on disk, whether to round the size to a multiple of the cluster size or not. There are also symbolic links which do not occupy disk space, and I can't find a way to distinguish them from normal directories. The size I get is much larger than the exact size as I'm unable to avoid calculating the sizes of those links. I guess there must be an API or something to get the exact file or directory size on disk. So what is it? Or is there a simpler / faster way to do that? Thanks for the help!