我得到一个无效的查询错误,当我加入其中name = [英] I get an invalid query error when I add WHERE Name =
问题描述
公共静态无效的命令(字符串vCommand,字符串计算机名,用户名字符串,字符串密码)
{
管理范围范围= NULL;
ConnectionOptions ConnOptions = NULL;
的ObjectQuery ObjQuery = NULL;
ManagementObjectSearcher ObjSearcher = NULL;
试
{
ConnOptions =新ConnectionOptions();
ConnOptions.Impersonation = ImpersonationLevel.Impersonate;
ConnOptions.EnablePrivileges = TRUE;
//本地机器
如果(machineName.ToUpper()== Environment.MachineName.ToUpper())
SCOPE =新的管理范围(@\ROOT\CIMV2,ConnOptions) ;
,否则
{
//远程机器
ConnOptions.Username =用户名;
ConnOptions.Password =密码;
SCOPE =新的管理范围(@\\+计算机名+ @\ROOT\CIMV2,ConnOptions);
}
Scope.Connect();
ObjQuery =新的ObjectQuery(SELECT * FROM Win32_Directory其中name ='C:\\0stuff');
ObjSearcher =新ManagementObjectSearcher(适用范围,ObjQuery);
的foreach(在ObjSearcher.Get的ManagementObject OBJ())//错误这里发生
{这里
//代码
}
如果(ObjSearcher!= NULL)
{
ObjSearcher.Dispose();
}
}
赶上(异常前)
{
罚球前;
}
}
}
如果我只用ObjQuery =新的ObjectQuery(SELECT * FROM Win32_Directory);,我得到一点问题都没有。
但只要我尝试使用WHERE名称= X ,我得到一个无效查询错误。
我不知道什么是错。 (之前有人问,是c:\0stuff存在)。
您需要使用逐字字符串 @...
来防止反斜杠被视为在C#中的转义序列:
@SELECT * FROM Win32_Directory其中name ='C:\\0stuff'
如果没有 @
,实际上是发送看起来像这样的查询:
选择* FROM Win32_Directory其中name ='C:\0stuff'
注意,反斜杠不再正确转义。
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;
}
}
}
If I use only "ObjQuery = new ObjectQuery("SELECT * FROM Win32_Directory");", I get no problem at all.
But as soon as I try to use "WHERE Name = X", I get an "invalid query" error.
I don't know what is wrong. (and before someone ask, yes c:\0stuff exist).
You need to use a verbatim string literal @"..."
to prevent the backslash being treated as an escape sequence in C#:
@"SELECT * FROM Win32_Directory WHERE Name = 'c:\\0stuff'"
Without the @
the query that is actually sent will look like this:
SELECT * FROM Win32_Directory WHERE Name = 'c:\0stuff'
Notice that the backslash is no longer properly escaped.
这篇关于我得到一个无效的查询错误,当我加入其中name =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!