如何使用 Objective-C 获取任何文件的文件类型描述?

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

我希望能够获取我 mac 上任何文件的文件类型(或文件种类)。这可以是一个包,一个有或没有扩展名的文件。有很多使用 UTType 的方法,但依赖于知道路径扩展,这不是我想要的。

如何使用 Objective-C 以编程方式获取文件的 Finder 信息中显示的确切文件类型描述字符串?

示例:

"/bin/echo" ==> "Unix 可执行文件"

提前致谢。

您可以使用文件的-[NSURL resourceValuesForKeys:error:] to ask for the localized type description

#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);
        }
    }
}

在我的系统上,这会生成与您在 Finder 中看到的相同的“Unix 可执行文件”值。


在Swift中:

import Foundation

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