4

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?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
colosso
  • 2,525
  • 3
  • 25
  • 49

4 Answers4

24

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();    
Heinzi
  • 167,459
  • 57
  • 363
  • 519
4

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 
}
Joe
  • 122,218
  • 32
  • 205
  • 338
  • 1
    According to this MSDN page ( http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited(v=vs.110).aspx ) you also need to set `execute.EnableRaisingEvents = true` in order for `execute.WaitForExit()` to work properly. – Matt Klein Jul 28 '14 at 21:48
  • @MattKlein - from what I read in the Remarks section of that link, `EnableRaisingEvents = true` is needed for asynchronous notification using the `Exited` event, but is not needed for synchronous notification using `WaitForExit`. – Joe Nov 24 '21 at 18:06
3

You can attach a handler to the Exited event on the Process object. Here's a link to the MSDN article on the event handler.

Matt T
  • 511
  • 2
  • 8
1

what you are looking for is the WaitForExit() function.

A Quick google will bring you to http://msdn.microsoft.com/en-us/library/ty0d8k56.aspx

or better still the Exited event that everyone else has mentioned ;)

dice
  • 2,820
  • 1
  • 23
  • 34