Best way to find out if any running process is running from a given file?

I need to check if another process is running based only on the name of the EXE file.

Currently, I get a list of processes and then request a property MainModule.FileName, however some processes throw Win32Exception"Unable to list process modules" when accessing a property MainModule. I am currently filtering into a "safe list", catching these access exceptions, this way:

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 to use exceptions like this.

Is there a better way to get a list of processes for which I can access a property MainModule, or even a better method to check if any process from a given file has been called?

+3
2

, System Idle, , , .

+6

        List<Process> processes = Process.GetProcesses().ToList();
        List<Process> safeProcesses  = processes .Select(X => 
        {
            try {  ProcessModule  pp = X.MainModule; return X; }

            catch { return null; }
        }).Where(X=>X!=null).ToList();
0

Source: https://habr.com/ru/post/1769709/


All Articles