我已经为我想向其发送命令并启动进程的内部服务器构建了一个网络服务。所以我想像这样向它发送命令:
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 执行相同的操作以获取错误消息。您可以生成一个后台线程以在主线程中读取标准输出的同时同步读取标准错误。
关于c# - 生成进程时如何重定向标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6099951/