2011-06-06 127 views
1

誰知道爲什麼我的查詢"select Name, ProcessID, Caption from Win32_Process where ProcessId='" + processIds[index] + "'"在我的程序C#返回查詢不能在C#中工作,但在PowerShell中工作

Column 'Name' does not belong to table Win32_Process 

在PowerShell中當我執行

Get-WmiObject -query "select Name, ProcessID, Caption from win32_process" 

它的作品!

String queryString = "select Name, ProcessID, Caption from Win32_Process where ProcessId='" + processIds[index] + "'"; 
       SelectQuery query = new SelectQuery(queryString); 

       ConnectionOptions options = new ConnectionOptions(); 
       options.Authentication = System.Management.AuthenticationLevel.PacketPrivacy; 


       ManagementScope scope = new System.Management.ManagementScope("\\root\\cimv2"); 
       ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query); 
       try 
       { 
        ManagementObjectCollection processes = searcher.Get(); 
        DataTable result = new DataTable(); 
        foreach (ManagementObject mo in processes) 
        { 
         DataRow row = result.NewRow(); 
         if (mo["Name"] != null) 
          row["Name"] = mo["Name"].ToString(); 
         row["ProcessId"] = Convert.ToInt32(mo["ProcessId"]); 
         if (mo["Caption"] != null) 
          row["Caption"] = mo["Caption"].ToString(); 
         result.Rows.Add(row); 
        } 

感謝您的幫助

回答

2

此代碼:

const string queryString = "SELECT Name, ProcessID, Caption FROM Win32_Process"; 

var scope = new ManagementScope(@"\root\cimv2"); 
var query = new ObjectQuery(queryString); 
var searcher = new ManagementObjectSearcher(scope, query); 
var objectCollection = searcher.Get(); 

foreach (var o in objectCollection) 
{ 
    Console.WriteLine("{0} {1} {2}", o["Name"], o["ProcessID"], o["Caption"]); 
} 

...工作正常,我。你的代碼究竟是如何工作的?

(順便說一下,您似乎沒有在options上做任何事情)。

更新:

它實際上是在抱怨,因爲你已經不是你DataTable設置列。我認爲你已經減少了太多的例子。你的DataTable被稱爲「Win32_Process」,是嗎?如果我把我的「偉業」:

var table = new DataTable("Albert"); 

我得到Column 'Name' does not belong to table Albert.

你需要做類似如下:

var table = new DataTable("Albert"); 
table.Columns.Add("Name"); 
table.Columns.Add("ProcessID", typeof(int)); 
table.Columns.Add("Caption"); 
+0

嗨,我改變我的代碼,我現在沒有現貨在Datarow中運行。 我想我有問題,當我嘗試行[「名稱」] =莫[「名稱」]。你知道爲什麼嗎 ? – 2011-06-06 08:57:12

+0

查看我的更新;你沒有添加任何列到你的'DataTable'中。 – 2011-06-06 08:57:47

+0

好吧我現在明白了,非常感謝你。你拯救了我的生命! – 2011-06-06 08:59:16

相關問題