2012-10-23 60 views
3

我想在遠程機器上搜索文件。我不知道確切的文件路徑,但我知道它在C:\ WINDOWS \ SYSTEM在遠程機器WMI上搜索文件C#

我的查詢是這樣的WMI

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

我得到無效的查詢錯誤。

該查詢是否有效?任何方式來指定路徑下?

回答

6

你在你的代碼

  1. 必須加倍逃脫\焦炭兩個問題,因爲這是在WMI
  2. 路徑屬性保留符號不能包含驅動器。

試試這個樣本

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

這不會工作,如果文件是在C:\ WINDOWS \ System32 \ drivers下。 它只看起來在C:\ Windows \ System32下。如何指定查看該路徑下的所有文件夾? –

+1

您可以使用'LIKE'運算符並以這種方式重寫WQL語句'SELECT * FROM CIM_DataFile Where Drive ='{0}'AND Path LIKE'%{1}%''但這會花費很多時間,因爲WMI將掃描整個驅動器以查找匹配項。我認爲最好的方法是使用'CIM_DataFile'和'Win32_Directory'類構造一個遞歸函數。 – RRUZ

相關問題