Query doesn't work on c# but work on powershell
Anyone know why my query "select Name, ProcessID, Caption from Win32_Process where ProcessId='" + processIds[index] + "'"
return
Column 'Name' does not belong to table Win32_Process
in my program C#.
In powershell when I execute
Get-WmiObject -query "select Name, ProcessID, Caption from win32_process"
It's works !
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);
}
Thanks for your help
This code:
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"]);
}
...works fine for me. Exactly how is your code not working?
(You don't appear to be doing anything with options
, by the way).
Update:
It's actually complaining because you've not set up the columns in your DataTable
. I think that you've cut down your example too much. Your DataTable
is called "Win32_Process", yes? If I call mine "Albert":
var table = new DataTable("Albert");
I get Column 'Name' does not belong to table Albert.
You need to do something like the following:
var table = new DataTable("Albert");
table.Columns.Add("Name");
table.Columns.Add("ProcessID", typeof(int));
table.Columns.Add("Caption");
精彩评论