[英]How to redirect standard output when spawning a process
I've built a webservice for an internal server that I want to send a command to and have it launch a process. 我为内部服务器构建了一个Web服务,我想向该服务器发送命令并启动一个进程。 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 capture all the error messages and standard output generated by the executable. 我希望能够捕获可执行文件生成的所有错误消息和标准输出。 The executable could be anything like a console application or a powershell script. 可执行文件可以是控制台应用程序或Powershell脚本之类的东西。 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. 使用proc.StandardOutput.ReadToEnd()将重定向的输出流读取到末尾,并将其返回。
You may also want to set RedirectStandardError to True and do the same thing with proc.StandardError to get the error messages. 您可能还需要将RedirectStandardError设置为True,并使用proc.StandardError进行相同的操作以获取错误消息。 You can spawn a background thread to synchronously read standard error alongside the reading of standard output in the main thread. 您可以生成一个后台线程来同步读取标准错误,同时读取主线程中的标准输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.