有很多示例展示了如何重定向另一个应用程序的标准输出。但是,我想让应用程序保留其标准输出,并且仅在父进程中检索标准输出的副本。这可能吗?
我的场景:我有一些测试(使用 Visual Studio Test Runner),它们启动外部进程(服务器)来进行测试。服务器在其标准输出中输出许多有用的调试信息,我希望将其包含在我的测试结果中。
我可以捕获进程输出并通过 Trace.WriteLine 输出它,以便稍后在测试详细信息中显示它。不过,如果在测试运行时看到服务器窗口及其输出以查看当前进度(测试可能运行很长时间),那就太好了。
因此,我正在寻找复制此信息而不是简单地重定向它的方法。
有什么想法吗?
最佳答案
这对你有用吗?
var outputText = new StringBuilder();
var errorText = new StringBuilder();
using (var process = Process.Start(new ProcessStartInfo(
@"YourProgram.exe",
"arguments go here")
{
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
}))
{
process.OutputDataReceived += (sendingProcess, outLine) =>
{
outputText.AppendLine(outLine.Data); // capture the output
Console.Out.WriteLine(outLine.Data); // echo the output
}
process.ErrorDataReceived += (sendingProcess, errorLine) =>
{
errorText.AppendLine(errorLine.Data); // capture the error
Console.Error.WriteLine(errorLine.Data); // echo the error
}
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
// At this point, errorText and outputText StringBuilders
// have the captured text. The event handlers already echoed the
// output back to the console.
}
关于c# - 如何复制进程的标准输出(复制,而不是重定向)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7850352/