重定向进程输出 C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18588659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect process output C#
提问by Idanis
I would like to redirect the Process's standard output to a string for later parsing. I would also like to see the output on the screen, while the process is running, and not only when it finishes it's run.
我想将 Process 的标准输出重定向到一个字符串以供以后解析。我还想在进程运行时在屏幕上看到输出,而不仅仅是在它完成时才运行。
Is that even possible?
这甚至可能吗?
回答by nmaier
Sample from MSDN:
来自 MSDN 的示例:
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "Write500Lines.exe";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Also see OutputDataReceived
and BeginOutputReadLine()
for an alternative to ReadToEnd()
, that will better fulfill your "see output while the process is running" requirement.
另请参阅OutputDataReceived
和BeginOutputReadLine()
的替代方法ReadToEnd()
,这将更好地满足您的“在进程运行时查看输出”的要求。
回答by Ronak Patel
If you want to execute an exe from your c# application and get the output from it then you can use the below code
如果要从 c# 应用程序执行 exe 并从中获取输出,则可以使用以下代码
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "PATH TO YOUR FILE";
p.StartInfo.UseShellExecute = false;
p.StartInfo.Arguments = metalType + " " + graphHeight + " " + graphWidth;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.EnableRaisingEvents = true;
p.Start();
svgText = p.StandardOutput.ReadToEnd();
using(StreamReader s = p.StandardError)
{
string error = s.ReadToEnd();
p.WaitForExit(20000);
}
Don't forgete to write p.EnableRaisingEvents = true;
不要忘记写 p.EnableRaisingEvents = true;