WMI query on CMI_DataFile class yields “Invalid qu

2019-03-01 02:54发布

OK, here's what I'm doing distilled to only the System.Management calls:

Simple queries and Method invokes work over the same connection. This query won't. And the file exists on the remote machine. Clues?

myQuery = "Select * from CIM_DataFile Where Drive = 'C:' AND Path = '\\Users\\someguy\\Documents\\' AND FileName = 'Default' AND Extension = 'rdp'";

options = new ConnectionOptions();
options.Username = myUsername;
options.Password = myPassword;
options.Authority = "ntlmdomain:MYDOMAIN";
scope = new ManagementScope("\\\\REMOTEMACHINE\\root\\CIMV2", options);
scope.Connect();
searcher = new ManagementObjectSearcher(scope, new ObjectQuery(myQuery));
myResults = searcher.Get();

ManagementObjectSearcher.Get() gets me a ManagementException saying "Invalid query." A simpler query, like, say, "SELECT * FROM Win32_NetworkAdapter", works.

I tried to reduce the WHERE's to just one, i.e. "Select * from CIM_DataFile Where Extension = 'rdp'". It works, although obviously it doesn't get me what I want. (Before the edit I mistakenly thought it didn't work even then; see comments) I'm at the end of the rope here.

标签: c# .net wmi
1条回答
三岁会撩人
2楼-- · 2019-03-01 03:30

I am an idiot. Please don't beat me up.

Firstly, the query only works reliably if you pass ALL components of the file name in WHERE clauses.

Secondly, I had to double the backslashes in the path component, and I was doing it wrong. I did:

pathPath.Replace("\\", "\\\\");

Whereas what I had to do was:

pathPath = pathPath.Replace("\\", "\\\\");

That's right. I worked under the assumption that String.Replace() changed the string in-line. Bad C# newbie. Bad.

查看更多
登录 后发表回答