Alex Rivera | Logout

Where does Console.WriteLine go in Debug?

Asked 2008-10-30T14:42:59.557
36

I found this question, but I want to know something different: Does the output from Console.WriteLine go anywhere when debugging? I know that for it to go to the output window I should should Debug.WriteLine() or other methods, but where does the standard Console.WriteLine() go?

When debugging, you don't see the black console window / test log, so the real question is: How can I access/view this output during debugging?

Edit
Report

1 Answer

22

The console can redirect its output to any textwriter. If you implement a textwriter that writes to Diagnostics.Debug, you are all set.

Here's a textwriter that writes to the debugger.

using System.Diagnostics;
using System.IO;
using System.Text;

namespace TestConsole
{
    public class DebugTextWriter : TextWriter
    {
        public override Encoding Encoding
        {
            get { return Encoding.UTF8; }
        }

        // Required
        public override void Write(char value)
        {
            Debug.Write(value);
        }

        // Added for efficiency
        public override void Write(string value)
        {
            Debug.Write(value);
        }

        // Added for efficiency
        public override void WriteLine(string value)
        {
            Debug.WriteLine(value);
        }
    }
}

Since it uses Diagnostics.Debug, it will adhere to your compiler settings to whether it should write any output or not. This output can also be seen in Sysinternals DebugView.

Here's how you use it:

using System;

namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.SetOut(new DebugTextWriter());
            Console.WriteLine("This text goes to the Visual Studio output window.");
        }
    }
}

If you want to see the output in Sysinternals DebugView when you are compiling in Release mode, you can use a TextWriter that writes to the OutputDebugString API. It could look like this:

using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace TestConsole
{
    public class OutputDebugStringTextWriter : TextWriter
    {
        [DllImport("kernel32.dll")]
        static extern void OutputDebugString(string lpOutputString);

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

        // Required
    
answered 2011-04-07T07:58:09.640

Your Answer