C# check if a process exists then close it

Try this to avoid the race condition in which a process closes after the first call to GetProcessesByName:

Process[] processes = Process.GetProcessesByName("ProcessName");
if (processes.Length > 0)
    processes[0].CloseMainWindow();

If you're planning to deploy this application on a wide range of machines, you will want to know that this code can sometimes fail.

The Process class in .NET is based on Windows performance counters, which on some machines can be disabled through the registry. When this happens, the call to the Process.GetProcessesByName method will throw an exception.

I think this situation is typical for machines with various "clean up / performance tuning" applications which, among other stuff, disable the performance counters in order to supposedly improve the machine's performance.

In the past this has repeatedly caused me pain with some percentage of my customers' client machines, which led me to explore other (if somewhat limited or cumbersome) alternatives, like making calls to Win API directly using PInvoke to iterate over the processes.

Another possible solution would be to ensure that your installer or application enables performance counters, or at least knows how to deal with them being disabled.


How about

if (Process.GetProcessesByName("ProcessName").Length > 0) {...}

Tags:

C#