Get InvalidOperationException when calling GetOwner

In the following code:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Management; using System.Diagnostics; namespace Test { class Program { static void Main(string[] args) { string javaProcWql = string.Format("SELECT ProcessId, Name, CommandLine FROM Win32_Process WHERE Name = '{0}' AND CommandLine LIKE '%{1}%'", "firefox.exe", "firefox"); ManagementObjectSearcher mos = new ManagementObjectSearcher(javaProcWql); foreach (ManagementObject mo in mos.Get()) { Console.WriteLine(mo["ProcessId"]); string[] userinfo = new string[2]; mo.InvokeMethod("GetOwner", (object[])userinfo); Console.WriteLine("ha ha --> " + userinfo[1] + "\\" + userinfo[0]); } } } } 

I get an InvalidOperationException , and the message along with the exception is

"Operation is not valid due to the current state of the object"

What is wrong here?

+4
source share
2 answers

I have found a solution. The request should look like this:

 string.format( "SELECT * FROM Win32_Process WHERE Name = '{0}' AND CommandLine LIKE '%{1}%'", "firefox.exe", "firefox" ) 

My explanation is an assumption, as I am not a programming specialist on Windows or .NET. In the original request (see Question), I selected the fields, but by specifying * , I select the objects, so I can call methods on them.

+6
source

The GetOwner method must process the field.

add the "Pen" field to select the status:

 SELECT Handle, ProcessId, Name, CommandLine FROM Win32_Process where ... 
+1
source

All Articles