Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

.net - Redirect stdout+stderr on a C# Windows service

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...