我需要动态确定WMI类的哪个属性是C#中的主键.
我可以使用CIM Studio或WMI Delphi Code Creator手动查找此信息,但我需要查找类的所有属性名称和标记哪些是键/键...我已经知道如何查找属性名称一类.
手动识别密钥在相关的答案中有所涉及,我希望作者(我正在看RRUZ)可能能够让我了解他们如何找到密钥(或任何可能知道的人).
非常感谢.
要获取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();
}
}
}
Run Code Online (Sandbox Code Playgroud)