Search code examples
c#.netwindowsprocesslocking

How to prevent to run an exe from two different computers


I developed a C# form application available as an exe file on a company server, accessible to all computers. I need to prevent someone from running it when it's already running on any computer.

I've looked at other solutions in SO but they are working fine only if the same computer runs the exe two times.

  1. Preventing multiple process instances of a single executable
  2. How to prevent two instances of an application from doing the same thing at the same time?

Solution

  • Have a file writable by your users on the server. When the application starts, open that file for write and keep a reference to the Stream in a static field. When the application is closed, close the Stream. If the application crashes or the network is down, the file will be automatically released by the OS.

    For instance, in your Program.cs :

    private static Stream lockFile;
    public static void Main()
    {
      try
      {
        try
        {
          lockFile = File.OpenWrite(@"\\server\folder\lock.txt");
        }
        catch (IOException e)
        {
          int err = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
          if (err == 32)
          {
            MessageBox.Show("App already running on another computer");
            return;
          }
          throw; //You should handle it properly...
        }
    
        //... run the apps
      }
      finally
      {
        if (lockFile != null)
          lockFile.Dispose();
      }
    }
    

    Based on