重定向标准输出+标准错误上一个C#Windows服务

问题描述:

我写了一个Windows服务在C#中使用 ServiceBase的帮手。在其执行上的外部机DLL一些程序被调用。烦人,这些程序写入到标准输出和/或标准错误的不受控制的方式,因为没有源给出了该DLL。

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 procedures write to stdout and/or stderr in a uncontrolled manner as no sources are given for this DLL.

是否有可能从C#服务的输出重定向到一个日志文件?

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

您可以通过的PInvoke这样做是为了的 SetStdHandle

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
}