我已经看到了至少两个关于WMI的其他问题,但没有一个问题对我的问题有答案,所以它是这样的;
我在我的代码中试验了WMI接口。基本上,这就是我现在所拥有的,并且它是有效的。但在我看来,我可以写得更有效率:
`public bool GetUsbStateById(string id) { bool returnValue = false;` try
{
ObjectQuery query = new ObjectQuery();
query.QueryString = string.Format("Select * From Win32_PnPDevice");
ManagementObjectSearcher mySearcher = new ManagementObjectSearcher(query);
List<ManagementObject> results = (from ManagementObject mo in mySearcher.Get().AsParallel()
where mo["SystemElement"].ToString().ToUpper().Contains(id.ToUpper())
select mo).ToList();
if (results.Count > 0)
returnValue = true;
}
catch (Exception ex)
{
// TODO: implement logging
}
return returnValue;
}
这里发生的事情是,我从ManagementObjectSearcher获得了一个ManagementObjects列表。这样做可以很好地工作,并且还会返回我期望的确切结果。
但在我看来这是多余的。因为,我首先得到整个列表,然后对其进行过滤。但是因为它使用WQL来填充列表,所以我假设我可以实现类似这样的东西:
query.QueryString = string.Format("Select * From Win32_PnPDevice where SystemElement Like '%{0}%'",id);
这会不断抛出查询不正确的exception。
所以我试着这样做:
query.QueryString = string.Format("Select SystemElement From Win32_PnPDevice);
这也行得通,所以接下来我尝试了Win32_PnPDevice.SystemElement,但这也行不通。
我在互联网上看到的任何例子都是这样的
Select * From Win32_Service Where Name Like "%SQL%"
但是c#不能解析%SQL%语句两边的双引号,使用\转义字符也不会产生任何结果。
为了测试我的代码和下面发布的代码,我使用了微软的WMI Code Creator
发布于 2013-02-18 22:20:48
如果你想在WMI中运行like查询,你可以使用下面的例子:
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
string strSearchText="win";
string strSearchQuery=string.Format("SELECT * FROM Win32_Service where Name like '%{0}%'",strSearchText);
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",strSearchQuery );
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_Service instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Name: {0}", queryObj["Name"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}但您不能以discussed身份在Win32_PNPDevice上应用like查询
https://stackoverflow.com/questions/14937699
复制相似问题