Redirect stdout+stderr on a C# Windows service

戏子无情 提交于 2019-11-26 07:42:13

问题


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.

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


回答1:


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
}



回答2:


Check out the Console.SetOut method.

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



来源:https://stackoverflow.com/questions/1579074/redirect-stdoutstderr-on-a-c-sharp-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!