Where does Console.WriteLine go in Debug?
Asked Answered
B

12

35

I found this question, but what I want to know is 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?

Edit 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?

Beadsman answered 30/10, 2008 at 14:42 Comment(1)
In Visual Studio uppermost menu choose Debug > Windows > Output. It shows all Console.WriteLine("Debug MyVariable: " + MyVariable) when you get to them. Set breakpoint before, debug, and then use F11 to step through code line by line.Polled
L
21

The console can redirect it's 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 wether 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
        public override void Write(char value)
        {
            OutputDebugString(value.ToString());
        }

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

        //Added for efficiency
        public override void WriteLine(string value)
        {
            OutputDebugString(value);
        }
    }
}
Lailaibach answered 7/4, 2011 at 7:58 Comment(3)
"it will adhere to your compiler settings to wether it should write any output or not" Where does output go?Cedeno
@Cedeno Diagnostics.Debug writes to the Output window in Visual Studio when debugging. Release compilation will normally remove the Debug statements.Lailaibach
Ah, what every programmer longs to do - write low-level output routines.Chalice
V
11

NullStream, which is defined as "A Stream with no backing store.". All the methods do nothing or return nothing. It is an internal class to Stream. The following code is taken from Microsoft's source code.

Basically, when one of the Console write methods is call the first time, a call is made to the Windows API function GetStdHandle for "standard output". If no handle is returned a NullStream is created and used.

Samuel's answer is correct and provides general information. To actually redirect Console output, regardless of the project type, use Console.SetOut(New System.IO.StreamWriter("C:\ConsoleOutput.txt")), which is a simple example.

Directing Console, Debug, and Trace to File

To answer your question directly. Use the ConsoleTraceListener and a StreamWriter to direct all three outputs to a file. I use the following for development only.

    Dim oLogFile As New System.IO.StreamWriter("C:\ConsoleOutput.txt")
    oLogFile.AutoFlush = True 'so we do not have to worry about flushing before application exit

    Console.SetOut(oLogFile)

    'note, writing to debug and trace causes output on console, so you will get double output in log file
    Dim oListener As New ConsoleTraceListener
    Debug.Listeners.Add(oListener)
    Trace.Listeners.Add(oListener)

NullStream

[Serializable]
private sealed class NullStream : Stream {
    internal NullStream() { }

    public override bool CanRead {
        get { return true; }
    }

    public override bool CanWrite {
        get { return true; }
    }

    public override bool CanSeek {
        get { return true; }
    }

    public override long Length {
        get { return 0; }
    }

    public override long Position {
        get { return 0; }
        set { }
    }

    // No need to override Close

    public override void Flush() {
    }

    public override int Read([In, Out] byte[] buffer, int offset, int count) {
        return 0;
    }

    public override int ReadByte() {
        return -1;
    }

    public override void Write(byte[] buffer, int offset, int count) {
    }

    public override void WriteByte(byte value) {
    }

    public override long Seek(long offset, SeekOrigin origin) {
        return 0;
    }

    public override void SetLength(long length) {
    }
} 
Vernavernacular answered 16/1, 2010 at 1:49 Comment(0)
O
5

The best solution for me was to change Console.WriteLine() to System.Diagnostics.Debug.WriteLine(). For example:

 catch (DbEntityValidationException dbEx)
 {
    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
       foreach (var validationError in validationErrors.ValidationErrors)
       {
          System.Diagnostics.Debug.WriteLine("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
       }
    }

Then you can view your errors as an object in the output window.

Obsolete answered 21/5, 2018 at 21:33 Comment(0)
S
3

Debug and Release do not control whether or not you get a console window. That is controlled by the project's output type. (Properties -> Application -> Output Type). Console Application will get you a console window which will visualize and receive input from the window into the Error, In, and Out streams in System.Console.

The System.Console class exposes several properties and methods for interacting with its streams even if you cannot see it. Most notably: Error, In, Out, SetError(), SetIn(), SetOut(), and the Read and Write methods.

Sumerology answered 30/10, 2008 at 15:15 Comment(0)
I
2

Visual Studio launches Windows programs (/target:winexe) with the stdin/stdout/stderr redirected to Named Pipes. The other end of each pipe is owned by the VS debugger and anything read on stderr/stdout is displayed in the Debug Output Window. Hence, Console.Write auto-magically appears in the VS Debug output. Note that this does not happen if you attach to an already started process (since the redirect trick can only be done at process launch time).

When launching console programs (/target:exe) this redirect does not occur so the Console.Write goes tothe actual console (or wherever the stdout is redirected).

I couldn't find anything that documents this behavior, is just my conclusion from investigating how VS launches and debugs apps.

Incorrect answered 15/11, 2017 at 12:1 Comment(1)
It seems VS2019 redirects STDOUT to the "Immediate Window".Malediction
B
2

Just add using System.Diagnostics; to your namespace. Then, use Debug instead of Console.
Example: Debug.WriteLine("Hello World");
Finally, press Ctrl+Alt+O to open the output window. Your text will be printed there. This window usually appears docked at the bottom of Visual Studio, but it can be dragged out and moved anywhere.
NOTE: There will be a dropdown box in the upper left corner that is called "Show output from:"
• "Debug" will need to be selected.
Alternatively, the output window can also be opened by selecting clicking the view tab and selecting Output.

Bastia answered 7/9, 2022 at 0:37 Comment(0)
G
1

I'll actually second James on this one.

http://www.csharp411.com/console-output-from-winforms-application

describes it in gross detail (if directing output to a file is enough though then you could easily use amissico's method). Most of the methods they describe mimic those described in http://dslweb.nwnexus.com/~ast/dload/guicon.htm

Changing your project to a "console" project would have a similar effect, as mentioned. Cheers!

Giacobo answered 13/3, 2011 at 4:59 Comment(0)
G
0

It goes to the console (standard output) or to the stream that the console is set to.

Godinez answered 30/10, 2008 at 14:44 Comment(1)
I think that's what the question is asking, 'what console', 'where is the console'?Saveloy
P
0

As already commented on OP's question:

No need to write additional code

In Visual Studio uppermost menu choose

Debug > Windows > Output

The output windows will only be visible in debug mode and it will show all e.g. Console.WriteLine("Debug MyVariable: " + MyVariable) when you get to them.

Set a breakpoint before (click the different-coloured empty area before the line number at the start of a chosen line), debug (F5), and then step through code line by line (F11) until you do.

Polled answered 12/3, 2020 at 14:37 Comment(0)
L
0

This is what i use, in globalusings.cs file, then it allows all Console.WriteLine("...") to output in Output window even in Debug mode.

#if DEBUG
global using Console = System.Diagnostics.Debug;
#endif
Leticialetisha answered 6/5 at 8:9 Comment(0)
W
-1

Even in a WinForms app, you can create a console window, but you'll have to go through P/Invoke to call a Win32 method directly. See http://pinvoke.net/default.aspx/kernel32/AllocConsole.html

Waitress answered 30/10, 2008 at 15:8 Comment(0)
S
-3

Console.writeline() goes to a console window: the black command / dos prompt.

Seagoing answered 30/10, 2008 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.