4

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 InvalidOperationException and the message along with exception is

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

What is wrong here?

Xolve
  • 22,298
  • 21
  • 77
  • 125

2 Answers2

6

I found the solution. The query should be like:

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

My explanation is a guess as I am not an expert in programming on Windows or .NET . In original query (see question) I was selecting fields, but by specifying * I select the objects, so I can call the methods on them.

Xolve
  • 22,298
  • 21
  • 77
  • 125
3

GetOwner method need to Handle field.

add Handle field to select statment:

SELECT Handle, ProcessId, Name, CommandLine FROM Win32_Process where ...
Mohsen.Sharify
  • 259
  • 4
  • 11