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

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

问题描述

我调用一个方法,比如说,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天全站免登陆