I've built a webservice for an internal server that I want to send a command to and have it launch a process. So I want to send a command to it like this:
http://machine:999/execute?path=c:\scripts\dostuff.exe&args=-test
The endpoint would then do something like this:
public ActionResult(string path, string args)
{
var proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = path;
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.RedirectStandardOutput = true;
//Hook into all standard output here
//Block until process is returned - Async Controller action
return Content(output.ToString())
}
I want to be able to c开发者_Go百科apture all the error messages and standard output generated by the executable. The executable could be anything like a console application or a powershell script. What's the best approach for doing something like this?
Use proc.StandardOutput.ReadToEnd() to read the redirected output stream to the end, and return that.
You may also want to set RedirectStandardError to True and do the same thing with proc.StandardError to get the error messages. You can spawn a background thread to synchronously read standard error alongside the reading of standard output in the main thread.
精彩评论