是否有可能拦截控制台输出? [英] Is it possible to intercept Console output?

查看:322
本文介绍了是否有可能拦截控制台输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所说的方法,比方说, FizzBu​​zz(),在这我管不着。使用这个方法输出一堆东西到控制台 Console.WriteLine

I call a method, say, FizzBuzz(), over which I have no control. This method outputs a bunch of stuff to the Console using Console.WriteLine.

是否有可能对我来说,拦截由 FizzBu​​zz 方法生成的输出? 请注意,我的应用程序是一个控制台应用程序本身。

Is it possible for me to intercept the output being generated by the FizzBuzz method? Note that my application is a Console app itself.

推荐答案

是的,很可能的:

var consoleOut = new StringWriter();
Console.SetOut(consoleOut);
Console.WriteLine("This is intercepted."); // This is not written to console
File.WriteAllText("ConsoleOutput.txt", consoleOut.ToString());

后来,如果要停止截获控制台输出,使用如下修改:

Later on if you want to stop intercepting the console output, use modification below:

var stdOut = Console.Out;
// Above interceptor code here..
Console.SetOut(stdOut); // Now all output start going back to console window

还是 OpenStandardOutput 做,而不需要先保存标准流是相同的:

Or the OpenStandardOutput does the same without the need to save the standard stream first:

// Above interceptor code here..
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput); // Now all output starts flowing back to console

这篇关于是否有可能拦截控制台输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆