Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

What is wrong here?

like image 217
Xolve Avatar asked Jan 15 '23 22:01

Xolve


1 Answers

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.

like image 113
Xolve Avatar answered Jan 29 '23 03:01

Xolve