Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# detect process exit

Tags:

c#

.net

I have following code:

   private void fileSystemWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
    {
        System.Diagnostics.Process execute = new System.Diagnostics.Process();

        execute.StartInfo.FileName = e.FullPath;
        execute.Start();

        //Process now started, detect exit here

    }

The FileSystemWatcher is watching a folder where .exe files are getting saved into. The files which got saved into that folder are executed correctly. But when the opened exe closes another function should be triggered.

Is there a simple way to do that?

like image 288
colosso Avatar asked Nov 27 '22 07:11

colosso


2 Answers

Attach to the Process.Exited event. Example:

System.Diagnostics.Process execute = new System.Diagnostics.Process();    
execute.StartInfo.FileName = e.FullPath;    
execute.EnableRaisingEvents = true;

execute.Exited += (sender, e) => {
    Debug.WriteLine("Process exited with exit code " + execute.ExitCode.ToString());
}

execute.Start();    
like image 68
Heinzi Avatar answered Dec 06 '22 17:12

Heinzi


Process.WaitForExit.

And incidentally, since Process implements IDisposable, you really want:

using (System.Diagnostics.Process execute = new System.Diagnostics.Process())
{
    execute.StartInfo.FileName = e.FullPath; 
    execute.Start(); 

    //Process now started, detect exit here 
}
like image 31
Joe Avatar answered Dec 06 '22 15:12

Joe