I\'ve written a Windows service in C# using the ServiceBase
helper. During its execution some procedures on an external native DLL are called. Annoyingly, those
You can do this via PInvoke to SetStdHandle:
[DllImport("Kernel32.dll", SetLastError = true) ]
public static extern int SetStdHandle(int device, IntPtr handle);
// in your service, dispose on shutdown..
FileStream filestream;
StreamWriter streamwriter;
void Redirect()
{
int status;
IntPtr handle;
filestream = new FileStream("logfile.txt", FileMode.Create);
streamwriter = new StreamWriter(filestream);
streamwriter.AutoFlush = true;
Console.SetOut(streamwriter);
Console.SetError(streamwriter);
handle = filestream.Handle;
status = SetStdHandle(-11, handle); // set stdout
// Check status as needed
status = SetStdHandle(-12, handle); // set stderr
// Check status as needed
}
Check out the Console.SetOut method.
It will allow you to redirect console output to a TextWriter.