简体   繁体   English

重定向控制台。写入特定程序集

[英]Redirect Console.Write of specific assembly

In my C# application I am loading another assembly via reflection. 在我的C#应用​​程序中,我通过反射加载另一个程序集。

This other assembly writes to the console with the Console.Write functions. 该另一个程序集使用Console.Write函数写入控制台。

I would like to redirect the output to a log4net appender for this specific assembly only. 我只想将输出重定向到该特定程序集的log4net附加程序。 I would like all other assemblies to continue to output to the console. 我希望所有其他程序集继续输出到控制台。

How can I achieve this? 我该如何实现?

  1. Console class has static method SetOut , which redirects output to StreamWriter object. Console类具有静态方法SetOut ,该方法将输出重定向到StreamWriter对象。
  2. Write your own StreamWriter extension class to redirect console output if assembly the same as you want. 如果您要的汇编相同,请编写自己的StreamWriter扩展类以重定向控制台输出。 Just for exmple. 只是为了举例。

    public class Writer : StreamWriter { private readonly Assembly _assembly; 公共类Writer:StreamWriter {private只读Assembly _assembly;

     private readonly StreamWriter _stdout; public Writer(Assembly assembly) : base(Console.OpenStandardOutput()) { _assembly = assembly; _stdout = new StreamWriter(Console.OpenStandardOutput()); } public override void Write(string value) { var st = new StackTrace(); var curent = st.GetFrames(); foreach (var frame in curent) { if (frame.GetMethod().Module.Assembly == _assembly) { _stdout.Write("Redirected: " + value); _stdout.Flush(); return; } } base.Write(value); this.Flush(); } 

    } }

Threre may be some occasions, such as one assembly calls method, that writes to console from another assembly. 在某些场合,例如一个程序集调用方法,会从另一个程序集写入控制台。 I don't know how to predict this behavior. 我不知道如何预测这种行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM