Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify if an app is running and start it if not

Tags:

c#

.net

process

wpf

I need to open an application if it is not already running.

Ex: I check if the application is running, if not I should run it for it to stay running.

I've tried:

System.Diagnostics.Process.Start ("location of the executable");

and it will work, however, do not have the specific path of the application to open.

like image 977
Bruno Heringer Avatar asked Aug 21 '12 17:08

Bruno Heringer


2 Answers

Based on your comment, detecting it is pretty straightforward. Just enumerate Process.GetProcesses() or look for it explicitly by Process.GetProcessByName(). There are various examples on the MSDN GetProcesses() documentation page.

Launching an arbitrary application, though, is not as simple. If it is in the environmental PATH variable, you can launch it without knowing the install location - Internet Explorer, for example, which you can run by just typing IExplore.exe in your Start->Run dialog on your machine.

If you are sure that the executable is going to be in the PATH, and by you implying in your post that you can already launch it via Process.Start(), that may suffice. You can just simply then put a conditional gate in to see if it is present in the running processes before invoking Process.Start() via a call to GetProcessByName - so something like:

var runningProcessByName = Process.GetProcessesByName("iexplore");
if (runningProcessByName.Length == 0)
{
    Process.Start("iexplore.exe");
}

You obviously would use the name of the application you are looking to check for / execute in place of "iexplore". Note that you are looking for the executable name without extension when you search for processes, yet are including it when you attempt to launch it.

Update

Here is a good example that can be easily modified for finding an arbitrary file or list of files in C#. Please bear in mind, if you are able to target any part of the path (for example, searching inside of Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), if you can be sure it is in a Program Files variant), the search will be considerably quicker. You may also want to consider storing the search result locally once the file is found, etc.:

Quickest way in C# to find a file in a directory with over 20,000 files

like image 173
Joseph Ferris Avatar answered Oct 07 '22 19:10

Joseph Ferris


Try mutex:

bool Creatednew;
Mutex mut=new Mutex(true,"someuniqeid",out Creatednew);
if(Creatednew)//this app isn't already running
{
//run your app
}
else
Debug.WriteLine("new app was terminated");
like image 3
czubehead Avatar answered Oct 07 '22 20:10

czubehead