Stefan
Stefan

Reputation: 144

Console.WriteLine does not work when attached to process in VS

If I have a code in C# .NET (winforms) which contains a Console.WriteLine("TEST"); and visual studio is attached to the process it doesn't write "TEST" in the output window. (application is correctly attached)

If I start my program normal with visual studio, it works.

Why does it not work in the first case?

Upvotes: 1

Views: 1874

Answers (1)

Remus Rusanu
Remus Rusanu

Reputation: 294407

Visual Studio, when debugging windows programs (/target:winexe) will launch them with the stdout and stderr redirected to Named Pipes. The other end of the named pipe is owned by the VS debugger and anything read on these pipes (ie. anything written by the app to stdout or stderr) will be displayed in the Debug Output window (which by no means is the debugged application Output window).

When attach to an application, this redirect can no longer be done (obviously, since the application is already started and stderr and stdin cannot be redirected post-factum). So the Console.Write is no longer auto-magically redirected to the Debug output.

Note that this stdout/stderr redircetion does not occur for console programs (/target:exe)

But there is a dedicated API to write Debug info: Debug.Write. This uses the OutputDebugString functions, which sends text to the attached debugger (if any). This works no matter when or how the debugger is attached, as is not dependent upon stdout/stderr redirection tricks.

Replace your Console.Write with Debug.Write.

Upvotes: 4

Related Questions