如何在生成流程时重定向标准输出
本文关键字:程时 重定向 标准输出 | 更新日期: 2023-09-27 17:57:40
我为一个内部服务器构建了一个Web服务,我想向该服务器发送命令并让它启动一个进程。所以我想向它发送这样的命令:
http://machine:999/execute?path=c:'scripts'dostuff.exe&args=-test
然后端点会做这样的事情:
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())
}
我希望能够捕获可执行文件生成的所有错误消息和标准输出。可执行文件可以是任何类似控制台应用程序或powershell脚本的内容。做这样的事情最好的方法是什么?
使用proc。StandardOutput.ReadToEnd()将重定向后的输出流读取到末尾,然后返回。
您可能还想将RedirectStandardError设置为True,并对proc执行同样的操作。StandardError以获取错误消息。您可以生成一个后台线程,在读取主线程中的标准输出的同时同步读取标准错误。