【问题标题】:Redirect process output C#重定向进程输出 C#
【发布时间】:2013-09-06 11:22:49
【问题描述】:

我想将 Process 的标准输出重定向到一个字符串以供以后解析。 我还想在进程运行时看到屏幕上的输出,而不仅仅是在它完成运行时。

这可能吗?

【问题讨论】:

标签: c# process redirectstandardoutput output-redirect


【解决方案1】:

如果您想从您的 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);
}

别忘了写 p.EnableRaisingEvents = true;

【讨论】:

  • EnableRaisingEvents 仅用于Process.Exited 事件。
【解决方案2】:

使用RedirectStandardOutput

来自 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();

另请参阅 OutputDataReceivedBeginOutputReadLine() 以获得 ReadToEnd() 的替代方案,这将更好地满足您的“在进程运行时查看输出”要求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 2010-11-20
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 2021-03-25
    相关资源
    最近更新 更多