WMI查询 - 使用并非所有操作系统都可用的属性

时间:2014-08-28 11:12:25

标签: c# wmi-query

在Windows 7上可以使用Pro Win32_OperatingSystem\OSArchitecture,但在Windows XP上不可用。我使用WMI代码生成器检查了这个。我应该如何更改以下代码以在两个操作系统(Win XP和Win 7)上工作?

ObjectQuery objectQuery = new ObjectQuery("SELECT OSArchitecture FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(objectQuery);
if (searcher.Get().Count == 0) // this line throw exception on Windows XP
    return null;

我知道我可以捕获异常,但我正在寻找更好的解决方案

1 个答案:

答案 0 :(得分:0)

这对我有用:

string strOSArchitecture = "";
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(objectQuery);
ManagementObjectCollection results = searcher.Get();

foreach (ManagementObject result in results)
{
   foreach (PropertyData property in result.Properties)
   {
      else if (property.Name.Equals("OSArchitecture"))
      {
         strOSArchitecture = result["OSArchitecture"].ToString();
      }
   }
}