objective-ccocoasizedirectorynsfilemanager

Easy way to get size of folder (ObjC/Cocoa)?


Right now I'm using this code to get the size of a folder:

NSArray *contents;
NSEnumerator *enumerator;
NSString *path;
contents = [[NSFileManager defaultManager] subpathsAtPath:folderPath];
enumerator = [contents objectEnumerator];
while (path = [enumerator nextObject]) {
    NSDictionary *fattrib = [[NSFileManager defaultManager] fileAttributesAtPath:[folderPath stringByAppendingPathComponent:path] traverseLink:YES];
    fileSize +=[fattrib fileSize];
}
        
[contents release];
[path release]; 

The problem is that its highly innacurate. It either adds a few megabytes or deducts a few megabytes from the actual size. For example I got the file size of an .app bundle and this method reported 16.2MB, whereas the actual thing is 15.8.

What's the best way to get the size of a folder?

Thanks


Solution

  • I needed to do this today myself, and I've found that the code in this post on the Cocoa-dev list is super fast and matches what Finder says to the byte. (don't forget to OR in the kFSCatInfoRsrcSizes flag so you get resource fork sizes, too!)

    If you need more explanation on how to use it, just leave a comment and I'll edit this post. =)