Reputation: 2943
I'm playing around with WMI. I'm attempting to modify the code below to fix a bug, namely that it originally queried by model. If you had two drives with identical models, it would only return the \\.\PHYSICALDEVICE of the first disk. Instead, I am now presenting a \\PHYSICALDEVICE: MODEL string to the user. They select this from the drop-down, I parse out the physical device and use that for the query.
Except that I keep getting an error "invalid query" returned on the MOS query
"SELECT * FROM Win32_DiskDrive WHERE DeviceID = '" + device + "'"
The query looks good to my eyes, but evidently isn't. Help appreciated.
Full code:
private void Form1_Load(object sender, EventArgs e)
{
//Select item from drop down menu
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher(
"SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject moDisk in mosDisks.Get())
{
string devid = moDisk["Model"].ToString();
string drvnum = moDisk["DeviceID"].ToString();
cmbHdd.Items.Add(drvnum + ": " + devid);
}
}
private void cmbHdd_SelectedIndexChanged(object sender, EventArgs e)
{
//update form with selected device
int i = cmbHdd.SelectedItem.ToString().IndexOf(':');
string device = cmbHdd.SelectedItem.ToString();//.Substring(0,i);
ManagementObjectSearcher mosDisks = new ManagementObjectSearcher(
"SELECT * FROM Win32_DiskDrive WHERE DeviceID = '" + device + "'");
foreach (ManagementObject moDisk in mosDisks.Get())
{
lblDeviceID.Text = "DeviceID: " + moDisk["DeviceID"].ToString();
}
}
Upvotes: 1
Views: 4610
Reputation: 97991
WMI requires that backslashes (\
) be doubled in queries.
Replace \
with \\
in the device
variable before insetting it to the query and see if it helps.
Upvotes: 3