如何处理WMI的管理异常

时间:2013-04-08 08:47:52

标签: c# .net wmi wmi-query

我正在使用WMI阅读处理器的详细信息WIN32_PROCESSOR。目前我正在尝试阅读这些属性:SELECT CAPTION,L2CACHESIZE,L3CACHESIZE FROM WIN32_PROCESSOR。所以我正在使用以下代码:

static void Main(string[] args)
{
    string strQuery = "SELECT CAPTION,L2CACHESIZE,L3CACHESIZE FROM WIN32_PROCESSOR";
    string strIPAddress = "XXX.XXX.X.XXX";
    DataTable dtProcessor = new DataTable();
    dtProcessor.Columns.Add("CAPTION");
    dtProcessor.Columns.Add("L2CACHESIZE");
    dtProcessor.Columns.Add("L3CACHESIZE");            

    ManagementScope scope = new ManagementScope(@"\\" + strIPAddress + @"\root\cimv2");
    SelectQuery query = new SelectQuery();
    query.QueryString = strQuery;
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    ManagementObjectCollection queryCollection = searcher.Get();
    foreach (ManagementObject mngmntObj in queryCollection)
    {
        DataRow dr = dtProcessor.NewRow();
        dr["CAPTION"] = mngmntObj["CAPTION"];
        dr["L2CACHESIZE"] = mngmntObj["L2CACHESIZE"];
        dr["L3CACHESIZE"] = mngmntObj["L3CACHESIZE"];
        dtProcessor.Rows.Add(dr);

    }
}

这在我的Windows Server 2008R2计算机上运行正常,但是相同的代码给我例外System.Management.ManagementException - > Invalid Query因为L3CACHESIZE在XP中不存在,如here所述。 通过读取存在的值来处理这个问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

如果要检查是否存在wmi属性,可以使用ManagementBaseObject.Properties属性并迭代集合。

尝试这样的事情

static void Main(string[] args)
{
    string strQuery = "SELECT * FROM WIN32_PROCESSOR";
    string strIPAddress = "XXX.XXX.X.XXX";
    DataTable dtProcessor = new DataTable();
    dtProcessor.Columns.Add("CAPTION");
    dtProcessor.Columns.Add("L2CACHESIZE");
    dtProcessor.Columns.Add("L3CACHESIZE");            

    ManagementScope scope = new ManagementScope(@"\\" + strIPAddress + @"\root\cimv2");
    SelectQuery query = new SelectQuery();
    query.QueryString = strQuery;
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
    ManagementObjectCollection queryCollection = searcher.Get();
    List<string> properties = new List<string>();
    foreach (ManagementObject mngmntObj in queryCollection)
    {

       if (properties.Count==0)
       {
         foreach (PropertyData property in mngmntObj.Properties)
         properties.Add(property.Name);
       }

        DataRow dr = dtProcessor.NewRow();
        dr["CAPTION"] = mngmntObj["CAPTION"];
        dr["L2CACHESIZE"] = mngmntObj["L2CACHESIZE"];
        if (properties.Contains("L3CACHESIZE", StringComparer.OrdinalIgnoreCase))
        {
        dr["L3CACHESIZE"] = mngmntObj["L3CACHESIZE"];
        }
        dtProcessor.Rows.Add(dr);

    }
}

对于这种特殊情况,如果您想获取与内存缓存相关的信息,请尝试Win32_CacheMemory