Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting external process from ASP.NET

Tags:

c#

.net

asp.net

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?

like image 908
Riri Avatar asked Feb 23 '09 19:02

Riri


2 Answers

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; 
}
like image 104
Cheeso Avatar answered Oct 17 '22 05:10

Cheeso


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"

like image 42
Al W Avatar answered Oct 17 '22 06:10

Al W