I've seen atleast two other questions regarding WMI but none had an answer to my question, so here it is;
I was experimenting with the WMI
interface in my code. Basically this is what i have right now and it works. But it seems to me i could write it more efficiently:
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;
}
So what happens here is that i get a list of ManagementObjects
from the ManagementObjectSearcher
. This works fine and also returns the exact results as i expect it to work.
But it seems redundant to me. Because, first i get the whole list, and then filter it. But because it uses WQL
to fill the list, i assumed that i could implement something like this:
query.QueryString = string.Format("Select * From Win32_PnPDevice where SystemElement Like '%{0}%'",id);
this keeps throwing an exception
that the query is not correct.
so i tried this instead:
query.QueryString = string.Format("Select SystemElement From Win32_PnPDevice);
This works as well, so next i tried Win32_PnPDevice.SystemElement
, but this didn't work either.
any examples i looked at on the internet showed something like this
Select * From Win32_Service
Where Name Like "%SQL%"
but c# can't parse the double quotes that surround the %SQL%
statement there, using an the \
escape character yielded no results either.
To test my code and the code posted below i used the WMI Code Creator from Microsoft