如何以编程方式确定哪个WMI属性是类的主键?

时间:2013-06-17 11:01:04

标签: c# wmi

我需要动态确定WMI类的哪个属性是C#中的主键。

我可以使用CIM StudioWMI Delphi Code Creator手动查找此信息,但我需要查找类的所有属性名称和标记哪些是键/键...我已经知道了如何查找类的属性名称。

密钥的手动识别包含在related answer中,我希望作者(我正在看RRUZ)可能能够让我知道他们如何找到钥匙(或其他任何人)可能知道)。

非常感谢。

2 个答案:

答案 0 :(得分:6)

要获取WMI类的键字段,必须迭代WMI类的qualifiers属性,然后搜索名为key的限定符,最后检查该值是否为true限定符为using System; using System.Collections.Generic; using System.Management; using System.Text; namespace GetWMI_Info { class Program { static string GetKeyField(string WmiCLass) { string key = null; ManagementClass manClass = new ManagementClass(WmiCLass); manClass.Options.UseAmendedQualifiers = true; foreach (PropertyData Property in manClass.Properties) foreach (QualifierData Qualifier in Property.Qualifiers) if (Qualifier.Name.Equals("key") && ((System.Boolean)Qualifier.Value)) return Property.Name; return key; } static void Main(string[] args) { try { Console.WriteLine(String.Format("The Key field of the WMI class {0} is {1}", "Win32_DiskPartition", GetKeyField("Win32_DiskPartition"))); Console.WriteLine(String.Format("The Key field of the WMI class {0} is {1}", "Win32_Process", GetKeyField("Win32_Process"))); } catch (Exception e) { Console.WriteLine(String.Format("Exception {0} Trace {1}", e.Message, e.StackTrace)); } Console.WriteLine("Press Enter to exit"); Console.Read(); } } }

试试这个样本

{{1}}

答案 1 :(得分:2)

对于那些感兴趣的人,我已经通过以下方式扩展了RRUZ的答案:

  • 允许对远程计算机运行查询,
  • 添加对具有多个主键的类的支持(与Win32_DeviceBus的情况一样)。

    static void Main(string[] args)
    {
        foreach (var key in GetPrimaryKeys(@"root\cimv2\win32_devicebus"))
        {
            Console.WriteLine(key);
        }
    }
    
    static List<string> GetPrimaryKeys(string classPath, string computer = ".")
    {
        var keys = new List<string>();
        var scope = new ManagementScope(string.Format(@"\\{0}\{1}", computer, System.IO.Path.GetDirectoryName(classPath)));
        var path = new ManagementPath(System.IO.Path.GetFileName(classPath));
        var options = new ObjectGetOptions(null, TimeSpan.MaxValue, true);
        using (var mc = new ManagementClass(scope, path, options))
        {
            foreach (var property in mc.Properties)
            {
                foreach (var qualifier in property.Qualifiers)
                {
                    if (qualifier.Name.Equals("key") && ((System.Boolean)qualifier.Value))
                    {
                        keys.Add(property.Name);
                        break;
                    }
                }
            }
        }
        return keys;
    }