简体   繁体   中英

I get an invalid query error when I add WHERE Name =

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM