2

我正在使用 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 中不存在,如此所述。通过读取存在的值来处理这个问题的最佳方法是什么?

4

1 回答 1

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

于 2013-04-08T16:19:20.900 回答