How can I get the file type description of any file using Objective-C?

Viewed 214

I want to be able to get the file type (or file kind) of any file on my mac. This could be a bundle, a file with or without extension. There are a lot of ways using UTType but that relay on knowing the path extension which is not what I want.

How to I get the exact file type description string that is displayed in thr Finder Info for a file but programmatically using Objective-C?

Example:

"/bin/echo" ==> "Unix executable"

enter image description here

Thanks in advance.

1 Answers

You can use -[NSURL resourceValuesForKeys:error:] to ask for the localized type description of the file:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSURL *url = [NSURL fileURLWithPath:@"/bin/echo"];
        
        NSError *error = nil;
        NSDictionary<NSURLResourceKey, id> *values = [url resourceValuesForKeys:@[NSURLLocalizedTypeDescriptionKey] error:&error];
        
        NSString *description = values[NSURLLocalizedTypeDescriptionKey];
        if (!description) {
            NSLog(@"Failed to get description: %@", error);
        } else {
            NSLog(@"%@", description);
        }
    }
}

On my system, this produces the same "Unix executable" value that you see in the Finder.


In Swift:

import Foundation

let url = URL(fileURLWithPath: "/bin/echo")
let values = try url.resourceValues(forKeys: [.localizedTypeDescriptionKey])
print(values.localizedTypeDescription) // Optional("Unix executable")
Related