Question

I would like to calculate the size of a directory and all its contents. All the solutions that I've come across either use NSFileManager (which doesn't take resource forks into account when calculating the file size) or this carbon code which uses deprecated functions.

How should we now get an accurate folder size using Cocoa ?

Was it helpful?

Solution

I solved this:

- (unsigned long long)folderSizeForURL:(NSURL *)url {

    NSArray *keys = @[ NSURLTotalFileSizeKey ];

    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager]
                                         enumeratorAtURL:url
                                         includingPropertiesForKeys:keys
                                         options:0
                                         errorHandler:^(NSURL *url, NSError *error) {
                                             // Handle the error.
                                             // Return YES if the enumeration should continue after the error.
                                             return YES;
                                         }];

    unsigned long long size = 0;

    for (NSURL *url in enumerator) {
        NSError *error;
        NSNumber *totalFileSize;
        [url getResourceValue:&totalFileSize forKey:NSURLTotalFileSizeKey error:&error];

        size += [totalFileSize longLongValue];
    }

    return size;
}

The result is exactly the same as the finder.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top