Dirty code trick

Here is a really quick and dirty piece of code that lets you get a Console window almost anywhere. Say from inside a Windows-service(maybe hosting a WCF). Sometimes you really need to get some text output for debugging, maybe on an environment where you cant access the eventlogs. Then this trick is handy.

Small C# example below:

using System.Runtime.InteropServices;


[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AllocConsole();


[DllImport("kernel32.dll", SetLastError = true)]
static extern bool FreeConsole();


AllocConsole();
Console.WriteLine(DateTime.Now.ToString() + " : Test Log");

Make sure to call AllocConsole() first.

When you are finished, simply call

FreeConsole();