1

The simple query works fine in PowerShell:

gwmi -Query "select * from Win32_DependentService where Antecedent='\\\\MYPC\\root\\cimv2:Win32_SystemDriver.Name=`"WdFilter`"'"

but it doesn't work in C#:

var scope = new ManagementScope("\\\\MYPC\\Root\\Cimv2");
scope.Connect();
var searcher = new ManagementObjectSearcher(scope, new ObjectQuery("select * from Win32_DependentService where Antecedent = '\\\\MYPC\\root\\cimv2:Win32_SystemDriver.Name=\"WdFilter\"'"));
ManagementObjectCollection queryCollection = searcher.Get();
var count = queryCollection.Count; // "Invalid query" exception here!!!

What is wrong with C# query? Thanks!

Andy
  • 11
  • 1
  • 1
    What error are you getting or just no results? If you getting exception it could be formatting problem. Try using String.Format to generate the query string. – zulqarnain Apr 13 '15 at 11:26
  • It is exception. "Invalid query" exception (see comment in the last code line). String.Format .. Hmm What is an idea for that? I just made copy&paste query string from the PS and replaced escape sequence for nested (") char. – Andy Apr 13 '15 at 12:25
  • I mean you might think escaping works sometimes but it may not be what you think. Try to escape the second `=` as well and see. – zulqarnain Apr 13 '15 at 12:40
  • escaping second = doesn't work as well. Moreover I see quite good query string in the debugger: "select * from Win32_DependentService where Antecedent = '\\MYPC\root\cimv2:Win32_SystemDriver.Name="WdFilter"' – Andy Apr 13 '15 at 12:54

1 Answers1

0

Fixed! We need more backslashes (up to eight! :). Right code is:

var scope = new ManagementScope("\\\\MYPC\\Root\\Cimv2");
var searcher = new ManagementObjectSearcher(scope, new ObjectQuery("select * from Win32_DependentService where Antecedent='\\\\\\\\MYPC\\\\root\\\\cimv2:Win32_SystemDriver.Name=\"WdFilter\"'"));
var queryCollection = searcher.Get();
var count = queryCollection.Count; // it's OK now

Hope it helps to somebody else :)

Andy
  • 11
  • 1