Search code examples
c#wmiwmi-query

WMI escape characters on string variable programatically


i have this working query

ManagementObject pnpdevice = new ManagementObjectSearcher(String.Format(
"select * from Win32_PnPEntity where DeviceID='{0}'",
"USB\\\\VID_046D&PID_C52B&MI_00\\\\6&48E0D58&0&0000")).First();

where i just realized that i needed to use quadruple slashes for one slash: two to escape in c#, two to escape in wmi.

my problem is how to do this programmatically instead of by hand. typically i would of course use the @ in front of the string to escape, so this works as well:

ManagementObject pnpdevice = new ManagementObjectSearcher(String.Format(
"select * from Win32_PnPEntity where DeviceID='{0}'",
@"USB\\VID_046D&PID_C52B&MI_00\\6&48E0D58&0&0000")).First();

but how do i do that with a string variable?

ManagementObject pnpdevice = new ManagementObjectSearcher(String.Format(
"select * from Win32_PnPEntity where DeviceID='{0}'",
device["DeviceID"].ToString())).First();

this doesn't have any of the escapes i need, and fails as an invalid query. writing it @device["DeviceID"].ToString() does not work.

any ideas?


Solution

  • i'm dumb, it was easy, just needed to add a replace to the string.

    ManagementObject pnpdevice = new ManagementObjectSearcher(String.Format(
        "select * from Win32_PnPEntity where DeviceID='{0}'",
        @device["DeviceID"].ToString().Replace("\\", "\\\\") )).First();