Pரதீப்
Pரதீப்

Reputation: 93694

check if exe is already running with same arguments c#

Currently I'm using the below function to stop my exe if the exe is already running

public static bool IsAlreadyRunning()
{
    string strLoc = Assembly.GetExecutingAssembly().Location;
    FileSystemInfo fileInfo = new FileInfo(strLoc);
    string sExeName = fileInfo.Name;
    bool bCreatedNew;

    Mutex mutex = new Mutex(true, "Global\\" + sExeName, out bCreatedNew);
    if (bCreatedNew)
        mutex.ReleaseMutex();

    return !bCreatedNew;
}

but my exe can run with different arguments, so I need to stop the exe only if there is another instance of my exe running with same arguments.

So is there a way to get the arguments from above code or any pointers to get this done ?

Upvotes: 1

Views: 1369

Answers (1)

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131227

You can use the arguments to generate the mutex name. The mutex only needs to have a unique name to work, it doesn't have to include the executable name.

The nice and clean method would be to pass the arguments to the method. The quick&dirty method is to use Environment.CommandLine to grab the entire command line or GetCommandLineArgs to get just the arguments.

For example :

var args=String.Join("-",Environment.GetArguments());
var mutexName=$@"Global\{sExeName}-{args}";
var mutex = new Mutex(true, mutexName, out bCreatedNew);

A better idea would be to hash the arguments first, and use the hash as the name. Using a hash method like the one in this answer, you can calculate the arguments has from the joined string :

static string GetSha256Hash(string input)
{
    var hasher=SHA256.Create();
    byte[] data = hasher.ComputeHash(Encoding.UTF8.GetBytes(input));

    StringBuilder sBuilder = new StringBuilder();

    // Loop through each byte of the hashed data 
    // and format each one as a hexadecimal string.
    for (int i = 0; i < data.Length; i++)
    {
        sBuilder.Append(data[i].ToString("x2"));
    }

    // Return the hexadecimal string.
    return sBuilder.ToString();
}

...

var args=String.Join("-",Environment.GetArguments());
var argHash=GetSha256Hash(args);
var mutexName=$@"Global\{sExeName}-{argHash}";
var mutex = new Mutex(true, mutexName, out bCreatedNew);

Upvotes: 2

Related Questions