public static void Command(string vCommand, string machineName, string username, string password)
{
ManagementScope Scope = null;
ConnectionOptions ConnOptions = null;
ObjectQuery ObjQuery = null;
ManagementObjectSearcher ObjSearcher = null;
try
{
ConnOptions = new ConnectionOptions();
ConnOptions.Impersonation = ImpersonationLevel.Impersonate;
ConnOptions.EnablePrivileges = true;
//local machine
if (machineName.ToUpper() == Environment.MachineName.ToUpper())
Scope = new ManagementScope(@"\ROOT\CIMV2", ConnOptions);
else
{
//remote machine
ConnOptions.Username = username;
ConnOptions.Password = password;
Scope = new ManagementScope(@"\\" + machineName + @"\ROOT\CIMV2", ConnOptions);
}
Scope.Connect();
ObjQuery = new ObjectQuery("SELECT * FROM Win32_Directory WHERE Name = 'c:\\0stuff'");
ObjSearcher = new ManagementObjectSearcher(Scope, ObjQuery);
foreach (ManagementObject obj in ObjSearcher.Get()) //ERROR HAPPEN HERE
{
//code here
}
if (ObjSearcher != null)
{
ObjSearcher.Dispose();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
如果我只使用“ObjQuery = new ObjectQuery(”SELECT * FROM Win32_Directory“);”我完全没问题。
但是一旦我尝试使用“WHERE Name = X”,我就会收到“无效查询”错误。
我不知道出了什么问题。 (在有人问之前,是的,c:\ 0stuff存在)。
答案 0 :(得分:3)
您需要使用逐字字符串文字@"..."
来防止反斜杠在C#中被视为转义序列:
@"SELECT * FROM Win32_Directory WHERE Name = 'c:\\0stuff'"
如果没有@
,实际发送的查询将如下所示:
SELECT * FROM Win32_Directory WHERE Name = 'c:\0stuff'
请注意,不再正确转义反斜杠。