A better way of finding out if any running process was launched from a given file?
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?
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.
I will use like
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();
精彩评论