20

I've written a Windows service in C# using the ServiceBase helper. During its execution, some procedures in an external native DLL are called. Annoyingly, those procedures write to stdout and/or stderr in an uncontrolled manner as no sources are given for this DLL.

Is it possible to redirect those outputs from the C# service to a log file?

2
  • is it starting up the DLL as a Process? or simply referencing the DLL? Commented Oct 16, 2009 at 16:40
  • You can't start a DLL as a process. This is a common issue. Commented Oct 16, 2009 at 16:42

2 Answers 2

32

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
}
Sign up to request clarification or add additional context in comments.

6 Comments

I've changed the line handle = filestream.Handler; by handle = filestream.SafeFileHandle.DangerousGetHandle(); because filestream.Handler is deprecated.
Any way to use this without a FileStream? (i.e. MemoryStream or similar)?
@ReedCopsey - Please see my reply to a similar comment on my new question: stackoverflow.com/questions/8555002/…
@Herchu you did realise the "Dangerous" in DangerousGetHandle? It is there for a reason: msdn.microsoft.com/en-us/library/…
@RuiMarques Yeah, they call me Danger for a reason! :) Seriously now; that was 2009. If I happen to need it again I'll write it following Steve's solution.
|
0

Check out the Console.SetOut method.

It will allow you to redirect console output to a TextWriter.

3 Comments

Depending on how the DLL is written, that won't redirect the DLLs output to the console, though. Typically, it works, but not always.
Reed, so what does it depend on?
To my recent experience, captures only the output that the C# code writes to the Console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.