1

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()
invertigo
  • 6,336
  • 5
  • 39
  • 64
  • Did you try with Process.GetProcessesByName()? – Adriano Repetti Jul 30 '14 at 22:37
  • I don't reliably have the name of the process, only the file name of the executable that started the process. FWIW, all I care about in this case is are there any processes started by this executable? – invertigo Jul 30 '14 at 22:57
  • same goes for checking Process.ProcessName (unless someone can tell me otherwise of course) – invertigo Jul 30 '14 at 22:58
  • 1
    Anyway I don't think it's a problem. Not every process can be accessed and it's a _not so exceptional exception_. What you _may_ do (if process you're searching is 32 bit) is to delegate this search to an external process (one 32 bit and one 64 bit, sadly AFAIK you can't force AnyCPU to execute as you prefer unless you use corflags). – Adriano Repetti Jul 31 '14 at 07:17
  • Possible solution/duplicate? http://stackoverflow.com/q/5497064/945456 – Jeff B May 31 '16 at 16:40

0 Answers0