Redirect stdout+stderr on a C# Windows service

前端 未结 2 470
逝去的感伤
逝去的感伤 2020-11-27 19:58

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

相关标签:
2条回答
  • 2020-11-27 20:07

    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
    }
    
    0 讨论(0)
  • 2020-11-27 20:20

    Check out the Console.SetOut method.

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

    0 讨论(0)
提交回复
热议问题