简体   繁体   中英

Searching for a File on Remote Machine WMI C#

I want to search for a file on remote machine. I don't know the EXACT file path but I know its under C:\\Windows\\System

My query is something like this in WMI

string querystr = "SELECT * FROM CIM_DataFile Where Path='C:\\Windows\\System'";
ObjectQuery query = new ObjectQuery(querystr );
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, query);

I get invalid query error.

Is the query valid ? Any way to specify Path Under ?

You have two issues in your code

  1. you must double escape the \\ char, because this is a reserved symbol in the WMI
  2. the path property must not include the drive.

try this sample

using System;
using System.Collections.Generic;
using System.Management;
using System.Text;

namespace GetWMI_Info
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                string ComputerName = "localhost";
                ManagementScope Scope;                

                if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) 
                {
                    ConnectionOptions Conn = new ConnectionOptions();
                    Conn.Username  = "";
                    Conn.Password  = "";
                    Conn.Authority = "ntlmdomain:DOMAIN";
                    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), Conn);
                }
                else
                    Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);

                Scope.Connect();
                string Drive = "c:";
                //look how the \ char is escaped. 
                string Path = "\\\\Windows\\\\System32\\\\";
                ObjectQuery Query = new ObjectQuery(string.Format("SELECT * FROM CIM_DataFile Where Drive='{0}' AND Path='{1}' ", Drive, Path));

                ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);

                foreach (ManagementObject WmiObject in Searcher.Get())
                {
                    Console.WriteLine("{0}",(string)WmiObject["Name"]);// String
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
            }
            Console.WriteLine("Press Enter to exit");
            Console.Read();
        }
    }
}

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