3

I am using .NET with C#.

I want to prevent two instances of the same executable to run at the same time, but I don't want to prevent the same process that is run from another folder.

For example, I have an executable that is in two different locations:

  • C:\MyProject\Master\Program.exe

  • C:\MyProject\Slave\Program.exe

These are the same .exe files, but in two different locations.

I want to allow one instance of Program.exe that is run from Master folder and one instance from the Slave folder, but no two of any.

I've tried to do this by checking the number of processes that have the same name (Process.GetProcessesByName), but then I can't differ the two.

The closest I have found is to get the Modules from the Process.

The first one in the list is ProcessModule of the exe. But I am not sure if this will always be the first one on the list. Is there any guarantee for that, or is there a better solution to the explained problem?

Kornelije Petak
  • 9,412
  • 15
  • 68
  • 96
  • 1
    I actually voted to close this as duplicate of [this](http://stackoverflow.com/questions/819773/run-single-instance-of-an-application-using-mutex), when I realized to nuance you give. Sorry. However, you could still follow that approach, but encode the complete path-name in the name of the mutex, thus allowing on instance per directory. – Christian.K May 07 '12 at 10:22
  • No problem. I don't even know if my explanation is clear enough. :) – Kornelije Petak May 07 '12 at 10:40

2 Answers2

1

I would use a global mutex instead of relying on the assembly name. Another application may be using the same file name for example.

See e.g. this answer: Run single instance of an application using Mutex

Community
  • 1
  • 1
Anders Forsgren
  • 10,827
  • 4
  • 40
  • 77
0

One way to do this is, by another service maybe, do something like this:

Process[] processes = Process.GetProcessesByName("Program");

will give you all the active processes of your program.

then you can get the directory from this:

string fullPath = process.MainModule.FileName;

Compare the directories of all instances and if two has the same folder, close one of them.

Mithir
  • 2,355
  • 2
  • 25
  • 37