我有一个使用 WMI 从服务器收集信息的类。问题是某些版本的 Windows 似乎有不同的可用/缺失属性,我似乎无法找到一种方法来检查集合以查看值是否存在,然后再尝试访问它们的值。
需要明确的是,我发现可以使用 wmiSingle.Properties.GetEnumerator() 遍历整个集合并检查每个属性名称值 - 但必须有更好的方法。对?
ManagementScope wmiScope = new ManagementScope("\\\\MyLaptop\\root\\cimv2");
ObjectQuery wmiVolumeQuery = new System.Management.ObjectQuery("SELECT * FROM Win32_Processor");
using (ManagementObjectSearcher wmiObjectSearcher = new ManagementObjectSearcher(wmiScope, wmiVolumeQuery))
{
using (ManagementObjectCollection wmiMany = wmiObjectSearcher.Get())
{
foreach (ManagementObject wmiSingle in wmiMany)
{
Console.WriteLine(wmiSingle["Name"]);
//This line will throw an exception. How do I test to see if
// "SomeProperty" exists before attempting to access the value?
//Console.WriteLine(wmiSingle["SomeProperty"]);
object somePropertyValue = wmiSingle.GetPropertyValue("SomeProperty");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我相信检查这一点的唯一方法是遍历属性
foreach (var prop in wmiSingle.Properties)
{
if(prop.Name == "SomeProperty")
{ /* do something */ }
}
Run Code Online (Sandbox Code Playgroud)
您也可以捕获异常 - 像这样
public static class Extensions
{
public static object TryGetProperty(this System.Management.ManagementObject wmiObj, string propertyName)
{
object retval;
try
{
retval = wmiObj.GetPropertyValue(propertyName);
}
catch (System.Management.ManagementException ex)
{
retval = null;
}
return retval;
}
}
Run Code Online (Sandbox Code Playgroud)
故意/故意引发异常通常效率不高;但是,也不是遍历整个集合以查找单个属性。