You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断StorageFile对象的Hidden属性状态?FileAttributes无该属性求方案

判断UWP中StorageFile是否隐藏的解决方案

嘿,这个问题我之前做UWP项目时也踩过坑!确实StorageFile自带的FileAttributes属性并不包含Hidden标识,但我们有两种靠谱的方法可以搞定:

方法一:使用FileInformation类(更简洁)

Windows.Storage.BulkAccess命名空间下的FileInformation类可以直接获取包含Hidden的文件属性,代码非常直观:

using Windows.Storage;
using Windows.Storage.BulkAccess;
using System.IO; // 引用System.IO来使用FileAttributes枚举

public bool IsFileHidden(StorageFile targetFile)
{
    if (targetFile == null)
        throw new ArgumentNullException(nameof(targetFile));
    
    var fileInfo = FileInformation.GetFileInformationFromStorageFile(targetFile);
    // 检查Attributes中是否包含Hidden标志
    return (fileInfo.Attributes & FileAttributes.Hidden) != 0;
}

这个方法不需要异步操作,直接同步获取属性,非常方便。

方法二:通过RetrievePropertiesAsync获取扩展属性

如果因为某些原因无法使用BulkAccess命名空间,也可以通过检索文件的系统属性来判断:

using Windows.Storage;
using System;

public async Task<bool> IsFileHiddenAsync(StorageFile targetFile)
{
    if (targetFile == null)
        throw new ArgumentNullException(nameof(targetFile));
    
    // 指定要获取的属性键:System.FileAttributes对应文件的DOS属性集合
    const string fileAttributesKey = "System.FileAttributes";
    var retrievedProperties = await targetFile.Properties.RetrievePropertiesAsync(new[] { fileAttributesKey });
    
    if (retrievedProperties.TryGetValue(fileAttributesKey, out object attributesValue) && attributesValue is uint attributes)
    {
        // Hidden属性的标志位是0x02,通过位运算判断是否包含该标志
        return (attributes & 0x02) != 0;
    }
    
    // 如果获取失败,可根据业务需求返回默认值(这里返回false)
    return false;
}

注意事项

  • 如果你访问的是应用沙箱外的文件(比如用户通过FileOpenPicker选择的文件),确保你的应用有对应的权限;如果是访问系统目录,可能需要在清单文件中声明broadFileSystemAccess能力。
  • 两种方法都能准确判断文件的隐藏状态,可根据项目的依赖情况选择。

内容的提问来源于stack exchange,提问作者Mg Bhadurudeen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:59:11