检查文件或目录是否被隐藏

Check if a file or directory is hidden

关于Mac,第一种情况,如果文件或目录的名称以“.”开头,则隐藏。

另一种情况,例如:

/Users/USER_NAME/Library
/bin

他们的名字不以“.”开头,但他们是隐藏的。

我得到了“/Users/USER_NAME/Library”的所有属性:

objective-c

NSError * error;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];

输出:

{
    NSFileCreationDate = "2019-06-04 23:44:56 +0000";
    NSFileExtensionHidden = 0;
    NSFileGroupOwnerAccountID = 20;
    NSFileGroupOwnerAccountName = staff;
    NSFileModificationDate = "2021-10-31 18:47:57 +0000";
    NSFileOwnerAccountID = 501;
    NSFileOwnerAccountName = xxxxxxxx;
    NSFilePosixPermissions = 448;
    NSFileProtectionKey = NSFileProtectionCompleteUntilFirstUserAuthentication;
    NSFileReferenceCount = 79;
    NSFileSize = 2528;
    NSFileSystemFileNumber = 360719;
    NSFileSystemNumber = 16777221;
    NSFileType = NSFileTypeDirectory;
}

没有找到是否隐藏相关属性。

您可以检查 fileURL 资源键 isHiddenKey fileURL 是否隐藏。请注意,如果文件名以句点开头,更改 isHidden 值将不会产生任何影响:

来自文档

If the resource is hidden because its name begins with a period, setting this value has no effect.


extension URL {
    var isHidden: Bool {
        get { (try? resourceValues(forKeys: [.isHiddenKey]))?.isHidden == true }
        set {
            var resourceValues = URLResourceValues()
            resourceValues.isHidden = newValue
            do {
                try setResourceValues(resourceValues)
            } catch {
                print("isHidden error:", error)
            }
        }
    }
}