本文介绍了重定向标准输出+标准错误上一个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这样做是为了的:
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
}
这篇关于重定向标准输出+标准错误上一个C#Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!