What is the best way to see if an application is currently running? This is specific to Windows environments, 32 or 64 bit. All I have to start with is the name of an executable (ie "TestApp.exe").
This is what I've tried, and while it works, I am somewhat concerned by the exceptions below.
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);
}
}
You'll notice I'm eating the exception, as one is always thrown, but they seem to be ignorable.
When I compile the application as Any CPU, I see these exceptions:
[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()
And as 32 bit:
[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()