“无效查询”异常没有明确原因

时间:2015-08-12 12:00:38

标签: c# .net wmi

下一次WMi查询有什么问题? (我得到了“无效查询”管理异常)。

        const string deviceName = "04157DF42C9B1109";

        string wmiQuery = string.Format("SELECT * FROM Win32_USBControllerDevice WHERE Antecedent LIKE '%{0}%'", deviceName);

        ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
        ManagementObjectCollection retObjectCollection = searcher.Get();

        foreach (ManagementObject retObject in retObjectCollection)
        {
            Console.WriteLine("[{0}]:{1}", retObject["Antecedent"], retObject["Dependent"]);
        }

2 个答案:

答案 0 :(得分:1)

我无法弄清楚如何修复原始错误,但可以使用以下方法作为解决方法:

string wmiQuery = string.Format("SELECT * FROM Win32_USBControllerDevice");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection retObjectCollection = searcher.Get();

var retObjectList = retObjectCollection.Cast<ManagementObject>()
    .Where(m => ((string)m["Antecedent"]).Contains(deviceName))
    .ToList();

foreach (ManagementObject retObject in retObjectList)
{
    Console.WriteLine("[{0}]:{1}", retObject["Antecedent"], retObject["Dependent"]);
}

我注意到其他人有同样的问题,有些人建议使用 ASSOCIATORS OF 语句(资源:https://superuser.com/questions/740564/wmi-query-based-on-antecedent-string)这是接受的答案,所以它也可能适合你。< / p>

答案 1 :(得分:0)

id建议您使用纯字符串而不是格式化它: 这样:

 string wmiQuery = "select * from Win32_USBControllerDevice where Antecedent like '%" + deviceName + "%'";

而不是:

 string wmiQuery = string.Format("SELECT * FROM Win32_USBControllerDevice WHERE Antecedent LIKE '%{0}%'", deviceName);

还有一件事:为什么你需要在字符串上使用const?也许这也可能是你的问题。