簡體   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