3

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!

user2594672
  • 129
  • 1
  • 2
  • 4

1 Answers1

8

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!

Pratik Singhal
  • 6,283
  • 10
  • 55
  • 97
  • It's neater but it doesn't seem to solve my problem. What I need is "size on disk". – user2594672 Feb 02 '14 at 04:46
  • I have already viewed the two webpages before I posted this question. Compressed files can sometimes share clusters and the formula is hence not suitable, thus I can hardly get the size on disk of directories. Also, I haven't found a way to tell symbolic links from normal files/folders. I'm already using `GetDiskFreeSpace` to find cluster size. All above is what I've thought and tried. – user2594672 Feb 02 '14 at 05:18