我必须根据EXE文件的名称检查另一个进程是否正在运行.
目前,我获取进程列表,然后查询MainModule.FileName属性,但是Win32Exception当您访问该MainModule属性时,某些进程会抛出"无法枚举进程模块" .目前我通过捕获这些访问异常来过滤到"安全列表":
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.
}
Run Code Online (Sandbox Code Playgroud)
不用说我真的不喜欢使用这样的例外.
有没有更好的方法来获取我可以访问该MainModule属性的进程列表,或者甚至是更好的方法来检查是否从给定文件生成了任何进程?