Searching for a File on Remote Machine WMI C#

你说的曾经没有我的故事 提交于 2019-12-06 08:44:27

问题


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 ?


回答1:


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();
        }
    }
}


来源:https://stackoverflow.com/questions/13022988/searching-for-a-file-on-remote-machine-wmi-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!