I need to start an external process from my web application. This means using System.Diagnostics.ProcessStartInfo to call out and execute a console app (exe). But I then need to somehow make sure nothing went wrong during it's execution and know when the application completed its work.
What's the best way to both catch all possible errors and find out when it's completed?
It's not so hard with the Process class. Though, the prior poster was correct - you need to be concerned about permissions.
private string RunProcess(string cmd)
{
System.Diagnostics.Process p;
p= new System.Diagnostics.Process();
if (cmd== null || cmd=="") {
return "no command given.";
}
string[] args= cmd.Split(new char[]{' '});
if (args== null || args.Length==0 || args[0].Length==0) {
return "no command provided.";
}
p.StartInfo.FileName= args[0];
if (args.Length>1) {
int startPoint= cmd.IndexOf(' ');
string s= cmd.Substring(startPoint, cmd.Length-startPoint);
p.StartInfo.Arguments= s;
}
p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.Start();
// must have the readToEnd BEFORE the WaitForExit(), to avoid a deadlock condition
string output= p.StandardOutput.ReadToEnd();
p.WaitForExit();
return output;
}
I sure hope you have control of the code for the external application or you are in for a lot of headaches. The MOST important thing to do is make sure there is no way for that application to hang and not terminate.
You can then use the WaitForExit(), ExitCode, StandardError, StandardOut to "catch all possible errors and find out when it's completed"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With