I made a WinForms application running on the .NET Framework 4.0. It writes on the parent console using the Console.WriteLine() method, after calling (once, at startup) the Win32 API function AttachConsole(-1).
It works flawlessly as long as I just need to show the output on screen. Unfortunately when I use a batch with a pipe redirection operator like this:
application.exe > output.txt
it just creates an empty file. Maybe there’s some problem related to the actual pipe being addressed when I use AttachConsole? Why the command prompt can’t catch the data and put it on the file? Does anyone know about any problems related to such a scenario?
Console.Outis initialised lazily. The first time you reference it the runtime callsGetStdHandle(STD_OUTPUT_HANDLE)to get the standard output handle. If this call occurs before the call toAttachConsoleyou get the handle to the file for redirection. If this call occurs afterwards you get the console output handle.The following class fixes up the standard output and error handles. If you launch your application from a console you’ll notice that any output appears after the next prompt. You can avoid this with
start /wait.