Question

Using this function:

 public bool CheckCallerStatus(string stConsumerName)
    {
        SelectQuery selectQuery = new SelectQuery("select ExecutablePath from Win32_Process where name='" +
                stConsumerName + "'");
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(selectQuery))
        {
            ManagementObjectCollection moc = searcher.Get();
            if (moc.Count > 1)
            {
                return true; // OK process is running
            }
            return false;
        }
     }

I can check whether the process, passed in as stConsumerName, is an active process (I use moc.Count > 1 and not moc.Count > 0 because I'm calling the function from the process I'm observing and trying to see if there are other active processes besides it). Each instance of my process is stored as an object in ManagementObjectCollection moc.

Now, I want to get the path of the process. I believe this information is stored in an object in moc and a simple foreach, like so:

string stFilePath = Empty.String;
foreach (ManagementObject process in moc)
{
    stFilePath = process["ExecutablePath"].ToString();
}

would return the path handsomely.

As you can see I'm storing the value of process["ExecutablePath"] to a string (and not to a List or array or somesuch) because I only care about the path of the first process (I'm assuming all the processes returned in moc are my process [the name is unique enough]).

My Question is: How do I access any one object in the ManagementObjectCollection? Such that I can set stFilePath = process["ExecutablePath"]; Since moc doesn't support indexing, moc.First() or moc.Single() won't help.

And a related Question: The ManagementObjectClass has a method GetEnumerable(). I've looked around (and of course in the MSDN Reference) and I don't really get it. Does GetEnumerable() return a indexed collection?

Was it helpful?

Solution

You can get the first object usig LINQ: moc.First(), or if you want to validate there is only one object use moc.Single().

EDIT: If ManagementObjectCollection doesn't implement IEnumerable<ManagementObject> than the above extension methods are indeed not implemented (this is not the same as indexer though). You can achieve the same thing manually though:

var enumerator = moc.GetEnumerator();
if(!enumerator.MoveNext()) throw new Exception("No elements");
ManagementObject obj = (ManagementObject) enumerator.Current;
string stFilePath = obj["ExecutablePath"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top