Close old instance of application

c#

Solution

This worked for me

if (pname.Length > 1)
{
    pname.Where(p => p.Id != Process.GetCurrentProcess().Id).First().Kill();
}

Problem

I'm developing a program, of which only one instance can run. I know I can apply mutex to prevent multiple instances from running. But I want it so if a new instance of an application runs, it should terminate the old one. The executable will always have the same name. I've tried running the following on the form load event; ``` Process[] pname = Process.GetProcessesByName(AppDomain.CurrentDomain.FriendlyName.Remove(AppDomain.CurrentDomain.FriendlyName.Length - 4)); if (pname.Length > 1) { pname[0].Kill(); } ``` Which actually works..... once every blue moon. Seriously, it works.. the first time around, the second time the application will simply not load. If I run it about 5 more times it might run. It doesn't seem too reliable, does anyone perhaps have a more elegant solution? Thanks!

Original source