重定向进程输出C#

本文关键字:输出 进程 重定向 | 更新日期: 2023-09-27 18:29:56

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

这可能吗?

重定向进程输出C#

使用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()的替代方案,这将更好地满足"在流程运行时查看输出"的要求。

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