如何在C#中获取所有文件类型的全部可用文件属性列表
获取Windows资源管理器中所有可查看文件属性的C#实现
要获取资源管理器中「更多」选项里显示的所有可查看文件属性列表,可通过调用Windows原生属性系统API实现,无需依赖第三方工具。以下是具体的C#代码实现:
步骤1:定义COM接口与原生方法
需要先定义Windows属性系统对应的COM接口和P/Invoke方法,用于访问系统属性描述信息:
using System; using System.Collections.Generic; using System.Runtime.InteropServices; [ComImport] [Guid("FCEFF153-E839-4CF3-A9E7-EA22832094B8")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPropertyDescriptionList { uint GetCount(); IPropertyDescription GetAt(uint index); } [ComImport] [Guid("6F79D558-3E96-4549-A1D1-7D75D2288814")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPropertyDescription { void GetPropertyKey(out PROPERTYKEY pkey); [PreserveSig] int GetDisplayName(out IntPtr ppszName); [PreserveSig] int IsViewable(out bool pfViewable); } [StructLayout(LayoutKind.Sequential)] public struct PROPERTYKEY { public Guid fmtid; public uint pid; } public static class PropertySystemNativeMethods { [DllImport("propsys.dll", CharSet = CharSet.Unicode)] public static extern int PSGetPropertyDescriptionListFromString( string pszPropList, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IPropertyDescriptionList ppv); }
步骤2:实现属性获取逻辑
编写方法遍历所有属性描述符,筛选出符合条件的可查看属性:
public static List<Tuple<string, PROPERTYKEY>> GetAllViewableFileProperties() { var viewableProperties = new List<Tuple<string, PROPERTYKEY>>(); Guid listInterfaceId = typeof(IPropertyDescriptionList).GUID; // 获取系统所有属性描述符列表 int resultCode = PropertySystemNativeMethods.PSGetPropertyDescriptionListFromString( "*", listInterfaceId, out IPropertyDescriptionList propertyList); if (resultCode != 0) throw new COMException("无法获取属性描述列表", resultCode); uint propertyCount = propertyList.GetCount(); for (uint i = 0; i < propertyCount; i++) { IPropertyDescription propertyDesc = propertyList.GetAt(i); // 筛选可查看属性 resultCode = propertyDesc.IsViewable(out bool isViewable); if (resultCode != 0 || !isViewable) continue; // 获取属性显示名称 resultCode = propertyDesc.GetDisplayName(out IntPtr displayNamePtr); if (resultCode != 0 || displayNamePtr == IntPtr.Zero) continue; string displayName = Marshal.PtrToStringUni(displayNamePtr); Marshal.FreeCoTaskMem(displayNamePtr); if (string.IsNullOrWhiteSpace(displayName)) continue; // 获取属性唯一标识键 propertyDesc.GetPropertyKey(out PROPERTYKEY propertyKey); viewableProperties.Add(Tuple.Create(displayName, propertyKey)); } Marshal.ReleaseComObject(propertyList); return viewableProperties; }
步骤3:使用示例
调用方法获取并输出结果:
var properties = GetAllViewableFileProperties(); foreach (var prop in properties) { Console.WriteLine($"显示名称: {prop.Item1} | 属性ID: {prop.Item2.fmtid:N} - {prop.Item2.pid}"); }
说明
- 此代码直接调用Windows的
propsys.dll,获取所有系统属性后筛选出可查看(IsViewable=true)且显示名称非空的属性,与Nirsoft工具筛选后的结果完全一致。 - 代码兼容.NET Framework及.NET Core/.NET 5+版本,仅能在Windows系统运行(依赖Windows属性系统)。
- 若需要获取属性的额外信息(如数据类型、描述文本),可扩展
IPropertyDescription接口,添加对应方法(参考MSDN中IPropertyDescription的官方定义)。
内容的提问来源于stack exchange,提问作者LesFerch
相关产品推荐
相关产品推荐

