Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way of finding out if any running process was launched from a given file?

Tags:

c#

I have to check whether another process is running, based only on the name of the EXE file.

Currently I get the process list and then query the MainModule.FileName property, however some processes throw Win32Exception "Unable to enumerate the process modules" when you access the MainModule property. Currently I am filtering to a 'safe list' by catching these access exceptions thus:

List<Process> processes = new List<Process>(Process.GetProcesses());

// Slow, but failsafe.  As we are dealing with core system
// data which we cannot filter easily, we have to use the absense of
// exceptions as a logic flow control.
List<Process> safeProcesses = new List<Process>();
foreach (Process p in processes)
{
    try
    {
        ProcessModule pm = p.MainModule;
        // Some system processes (like System and Idle)
        // will throw an exception when accessing the main module.
        // So if we got this far, we can add to the safe list
        safeProcesses.Add(p);
    }
    catch { } // Exception for logic flow only.
}

Needless to say I really don't like having to use exceptions like this.

Is there a better way to get the process list for which I can access the MainModule property, or even a better method of checking if any process was spawned from a given file?

like image 340
Dr Herbie Avatar asked Dec 05 '25 07:12

Dr Herbie


1 Answers

I think that there are only System and Idle processes that will throw the exception so you can filter them out before and you're ready to go.

like image 171
oleveau Avatar answered Dec 07 '25 19:12

oleveau