A better way of finding out if any running process was launched from a given file?
<p>I have to check whether another process is running, based only on the name of the EXE file.</p>

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

<pre><code>List&lt;Process&gt; processes = new List&lt;Process&gt;(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&lt;Process&gt; safeProcesses = new List&lt;Process&gt;();
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.
}
</code></pre>

<p>Needless to say I really don't like having to use exceptions like this.</p>

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