How to obtain the size of a Application Directory

2019-03-30 10:58发布

问题:

(NSString *)
getApplicationUsage{

    double directorySizeInBytes = 0.0f;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationDirectory, NSUserDomainMask, YES);

    NSString *pathStr = [paths objectAtIndex:0];

    pathStr = [pathStr stringByDeletingLastPathComponent];  //REMOVE THE LAST PATH COMPONENT i.e /Applications

    NSDirectoryEnumerator *enumrator = [[NSFileManager defaultManager] enumeratorAtPath:pathStr];


    for (NSString *itemPath in enumrator) {

        itemPath = [pathStr stringByAppendingPathComponent:itemPath];

        NSDictionary *attr  =   [[NSFileManager defaultManager] attributesOfItemAtPath:itemPath error:nil];

        directorySizeInBytes = directorySizeInBytes + [[attr objectForKey:NSFileSize] doubleValue];

    }


    NSString *applicationUsage = [NSString stringWithFormat:@"%0.0f MB",directorySizeInBytes /1000000];
    return applicationUsage;
}

回答1:

How about this?

- (unsigned long long) sizeOfFolderAtPath:(NSString *)path {
    NSArray *files = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:path error:nil];
    NSEnumerator *enumerator = [files objectEnumerator];
    NSString *fileName;
    unsigned long long size = 0;
    while (fileName = [enumerator nextObject]) {
        size += [[[NSFileManager defaultManager] fileAttributesAtPath:[folderPath stringByAppendingPathComponent:fileName] traverseLink:YES] fileSize];
    }
    return size;
}