1

Is there anything built-in that can redirect Console.WriteLine calls to System.Diagnostic.Debug-calls?

I was hoping for something like this:

public static void CallNastyConsoleWriteLineUsingFunction() {
    Console.WriteLine(GetImportantInformation());
}

[...]

var writer = DebugTextWriter();
TextWriter stdout = Console.Out;
try
{
    Console.SetOut(writer);
    CallNastyConsoleWriteLineUsingFunction();
}
finally
{
    Console.SetOut(stdout);
}

Or maybe even:

using(new ConsoleToDebugRedirector())
{
    CallNastyConsoleWriteLineUsingFunction();
}
johv
  • 4,424
  • 3
  • 26
  • 42

2 Answers2

2

You could do something like this:

public class Program
{
    public static void Main(string[] args)
    {
        using (new ConsoleRedirect<DebugTextWriter>())
        {
            Console.WriteLine("Testing testing...");
        }

        Console.WriteLine("Testing testing 2...");
        Console.ReadLine();
    }
}

public class ConsoleRedirect<T> : IDisposable
    where T : TextWriter, new()
{
    private readonly TextWriter _tmpTextWriter;

    public ConsoleRedirect()
    {
        _tmpTextWriter = Console.Out;
        Console.SetOut(new T());
    }

    public void Dispose()
    {
        Console.SetOut(_tmpTextWriter);
    }
}

public class DebugTextWriter : TextWriter
{
    public override void WriteLine(string value)
    {
        Debug.WriteLine(value);
    }

    public override void WriteLine(object value)
    {
        Debug.WriteLine(value);
    }

    public override void WriteLine(string format, params object[] arg)
    {
        Debug.WriteLine(format, arg);
    }

    public override Encoding Encoding
    {
        get { return Encoding.UTF8; }
    }
}

It will redirect all Console.WriteLine calls to Debug.WriteLine while inside the using statement. It is pretty cumbersome to override all the write methods of the TextWriter, but you could probably use the wrapper in this answer

Community
  • 1
  • 1
khellang
  • 17,550
  • 6
  • 64
  • 84
2

You can do the reverse. Use standard Debug/Trace calls and add a ConsoleTraceListener Class to your configuration. The net effect should be the same with standard coding/behavior.

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298