c# - 如何复制进程的标准输出(复制,而不是重定向)?

标签 c# .net unit-testing mstest stdout

有很多示例展示了如何重定向另一个应用程序的标准输出。但是,我想让应用程序保留其标准输出,并且仅在父进程中检索标准输出的副本。这可能吗?

我的场景:我有一些测试(使用 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/

相关文章:

ios - Swift 中的单元测试 - 通过 XCTAssertTrue 方法插入中断和/或返回

c# - 如何使用 LINQ 获取 id 的列表作为 int

c# - 找不到类型或命名空间名称 'Column'

python - 如何通过 unittest setUp 在 python 中正确使用 mock

c# - 如何显示两个日期之间的计算值,仅小时和分钟超过 C# 中的 24 小时差异

.net - 带有.Net的Oracle高级队列

apache-flex - 是否有编写好的单元测试的优秀示例 Flex 项目?

c# - 不支持的媒体类型 web api 发布

c# - csproj.csdat 文件有什么用

c# - 深色/浅色主题 Assets 限定符