Th3ms
Th3ms

Reputation: 11

How can I get process by name?

How can I get process by name?

For example, if the process name is "Test", it will do nothing, but if there isn't a name "Test", it will say MessageBox.Show("Cannot find process Test");

I used

foreach (var process in Process.GetProcessesByName("Test"))
{
    //do nothing
}

However, foreach doesn't have else, and I can't do that. Any ideas?

Upvotes: 1

Views: 2774

Answers (2)

RoadRunner
RoadRunner

Reputation: 26335

From the documentation for System.Diagnostics.Process.GetProcessesByName:

Returns Process[] An array of type Process that represents the process resources running the specified application or file.

Which tells us GetProcessByName will return an array of processes that share the same process name.

Instead, we can simply just check if the array is empty:

var processes = Process.GetProcessesByName("Test");

if (processes.Length == 0)
{
    MessageBox.Show("Cannot find process Test");
} 
else
{
    // found processes
    // iterate and do something with them
    foreach (var process in processes)
    {
        //do something
    }
}

Which will only show the message from the if block if no processes with the name "Test" could be found. Otherwise, you can iterate the found processes and do something with them in the else block.

Upvotes: 2

Marco Salerno
Marco Salerno

Reputation: 5201

Try this way:

var processes = Process.GetProcessesByName("Test");

if(processes.Length == 0)
{
    MessageBox.Show("Cannot find process Test");
}
else
{
    foreach(var process in processes)
    {
        //do something
    }
}

Upvotes: 3

Related Questions