Check if app is already running, and if kill it C#

4.9k views Asked by At

I know that Mutex can be used to determine if another instance of application is running, but can I find from Mutex the PID or name of the other instance? And if not from Mutex, is there another way around to kill other instance if it is running. This is kinda tricky, because it also must be bounded to user and it shouldn't use files to do the trick (I know that Mutex creates files, but those created by .NET via internal functions are OK).

Note that I need to get info of other instance to kill it.

Thanks for reading!

1

There are 1 answers

0
Nicholas Carey On BEST ANSWER

Something like this ought to do you:

static void Main(string[] args)
{
  HashSet<string> targets = new HashSet<string>( args.Select( a => new FileInfo(a).FullName ) , StringComparer.OrdinalIgnoreCase ) ;

  foreach ( Process p in Process.GetProcesses().Where( p => targets.Contains(p.MainModule.FileName) ) )
  {
    Console.WriteLine( "Killing process id '{0}' (pid={1}), main module: {2}" ,
      p.ProcessName ,
      p.Id ,
      p.MainModule.FileName
      ) ;
    try
    {
      p.Kill() ;
      Console.WriteLine("...Killed");
    }
    catch ( Exception e )
    {
      Console.WriteLine( "...well, that was unexpected. Error: {1}" , e.Message ) ;
    }
  }
  return;
}