查看某个应用程序当前是否正在运行的最佳方法是什么?这特定于Windows环境,32位或64位。我所要做的就是可执行文件的名称(即“TestApp.exe”)。
这是我尝试过的,虽然它有效,但我对下面的例外有些担心。
Process[] currentProcesses = Process.GetProcesses();
foreach (Process clsProcess in currentProcesses)
{
try
{
if (clsProcess.MainModule.FileName.Contains(nameOfExe))
{
Log.Info(string.Format("Application is running {0}", clsProcess.ProcessName));
return true;
}
}
catch (Win32Exception ex)
{
Log.Warn(ex);
}
}
你会注意到我正在吃这个例外,因为总是抛出一个,但是它们似乎是可以忽略的。
当我将应用程序编译为任何CPU时,我看到以下例外情况:
[7/30/2014 3:25:36 PM] WARN - Access is denied
System.ComponentModel.Win32Exception
at System.Diagnostics.ProcessManager.OpenProcess(Int32 processId, Int32 access, Boolean throwIfExited)
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.Process.get_MainModule()
[7/30/2014 3:25:36 PM] WARN - Unable to enumerate the process modules.
System.ComponentModel.Win32Exception
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.Process.get_MainModule()
和32位:
[7/30/2014 3:24:28 PM] WARN - A 32 bit processes cannot access modules of a 64 bit process. System.ComponentModel.Win32Exception
at System.Diagnostics.NtProcessManager.GetModuleInfos(Int32 processId, Boolean firstModuleOnly)
at System.Diagnostics.NtProcessManager.GetFirstModuleInfo(Int32 processId)
at System.Diagnostics.Process.get_MainModule()