Joannes
Joannes

Reputation: 81

folder size wrong

This code is correct but the folder size is wrong. If I change the directory the size is always wrong. For example the size of "%@/Caches/com.apple.Safari/Webpage Previews" is 23 MB, but I have 16.5 KB.

NSString *path = [NSString stringWithFormat:@"%@/Caches/com.apple.Safari/Webpage Previews", [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
    NSNumber *fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil] objectForKey:NSFileSize];
    resultsize += [fileSize unsignedLongLongValue];

also I used this but the size is always wrong:

NSFileManager *fm = [[NSFileManager alloc] init];    
    NSURL *LibraryURL = [[fm URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *previewsURL = [LibraryURL URLByAppendingPathComponent:@"Caches/com.apple.Safari/Webpage Previews"];

    resultSize += [[[fm attributesOfItemAtPath:[previewsURL path] error:nil] objectForKey:NSFileSize] unsignedIntegerValue];

Can you help me? Thanks.

Upvotes: 1

Views: 992

Answers (2)

mahal tertin
mahal tertin

Reputation: 3414

Lion has some kind of Cache for these cumulative sizes. Try on a server volume (Mac OS X Lion Server AFP):

  • Open a Folder with lots of Subfolders
  • Menu View > as List
  • Menu View > Arrange By > Size
  • Finder shows all subfolders in the "---" group
  • Menu View > Show View Options
  • check the box "Calculate all File Sizes"
  • now Finders groups the subfolders appropriately
  • and even when you close that window, disconnect server and connect again, these sizes are there faster and also when not arranged by size

-> where is this information stored? which API to use?

Upvotes: -1

Wevah
Wevah

Reputation: 28242

If you want to get the size of all the files in a folder, you'll need to iterate through the contents of the folder and get the sizes of the actual files:

unsigned long long totalSize = 0;
NSFileManager *fm = [[NSFileManager alloc] init];
NSURL *libraryURL = [[fm URLsForDirectory:NSLibraryDirectory inDomains:NSUserDomainMask] lastObject];
NSURL *previewsURL = [LibraryURL URLByAppendingPathComponent:@"Caches/com.apple.Safari/Webpage Previews"];

NSDirectoryEnumerator *enumerator = [fm enumeratorAtURL:previewsURL includingPropertiesForKeys:[NSArray arrayWithObject:NSURLFileSizeKey] options:0 errorHandler:nil /* or an actual error handler */];

for (NSURL *url in enumerator) {
    NSNumber *sizeNumber;
    if ([url getResourceValue:&sizeNumber forKey:NSURLFileSizeKey error:nil /* or an error */])
        totalSize += [sizeNumber unsignedLongLongValue]; 
}

(I haven't tested this.)

Upvotes: 5

Related Questions