繁体   English   中英

在远程计算机WMI C#上搜索文件

[英]Searching for a File on Remote Machine WMI C#

我想在远程机器上搜索文件。 我不知道EXACT文件路径,但我知道它在C:\\ Windows \\ System下

我的查询在WMI中是这样的

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

我得到无效的查询错误。

查询有效吗? 有什么方法可以指定Path Under吗?

您的代码中有两个问题

  1. 你必须双重转义\\ char,因为这是WMI中的保留符号
  2. path属性不能包含驱动器。

试试这个样本

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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