views:

3519

answers:

6

Hi,

the following C# program (built with csc hello.cs) prints just Hello via Console! on the console and Hello via OutputDebugString in the DebugView window. However, I cannot see either of the System.Diagnostics.* calls - does anybody know why that is?

using System;
using System.Runtime.InteropServices;
class Hello {
    [DllImport("kernel32.dll", CharSet=CharSet.Auto)]
    public static extern void OutputDebugString(string message);

    static void Main() {
        Console.Write( "Hello via Console!" );
        System.Diagnostics.Debug.Write( "Hello via Debug!" );
        System.Diagnostics.Trace.Write( "Hello via Trace!" );
        OutputDebugString( "Hello via OutputDebugString" );
    }
}

Is there maybe some special command line switches required for csc?

EDIT:

I'm not using Visual Studio for any of my development, this is pure commandline stuff.

A: 

While you are debugging in Visual Studio, display the "Output" window (View->Output). It will show there.

Pat
+2  A: 
Andreas Grech
+9  A: 

You need to add a TraceListener to see them appear on the Console.

TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(writer);

They also appear in the Visual Studio Output window when in Debug mode.

Jason
But do listeners show the results from OutputDebugString ?
Henk Holterman
A: 

The Console write methods write into standard I/O that's why you're able to see them readily. The Debug output methods write into the debug stream. You can show that by running your application in debug mode and watching the Output window in the IDE.

Paul Sasik
+3  A: 

As others have pointed out, listeners have to be registered in order to read these streams. Also note that Debug.Write will only function if the DEBUG build flag is set, while Trace.Write will only function if the TRACE build flag is set.

Setting the DEBUG and/or TRACE flags is easily done in the project properties in Visual Studio or by supplying the following arguments to csc.exe

/define:DEBUG;TRACE

Tormod Fjeldskår
How are these DEBUG and TRACE build flags set? I'm not using any IDE like Visual Studio, just the 'csc.exe' command line compiler.
Frerich Raabe
See revised answer
Tormod Fjeldskår
Excellent, defining DEBUG and/or TRACE on the command line makes my test work. Accepting this answer.
Frerich Raabe
+3  A: 

While debugging System.Diagnostics.Debug.WriteLine will display in the output window. (Ctrl+Alt+O)

You can also add a TraceListener to the Debug.Listeners collection to specify Debug.WriteLine calls to output in other locations.

Note: Debug.WriteLine calls may not display in the output window if you have the Visual Studio option "Redirect all Output Window text to the Immediate Window" checked under the menu Tools > Options > Debugging > General.

boardernin
Thanks for the tip. Solved my problem.
Gregory