How to write to a program's StdOut Stream directly in C#?

前端 未结 3 721
无人共我
无人共我 2021-01-02 21:46

I know that there\'re stdout/in/err for a program and I want to redirect a program\'s output to a file instead of the console output. And I now figure it out with the code b

相关标签:
3条回答
  • 2021-01-02 22:05

    You probably shouldn't set the stdout of your own process. The reason it's stdout is so that the caller (command line, whatever) can redirect it wherever it needs to, without your program having to know.

    That's how things like "type foo.txt | more" work. If the type command felt free to redefine stdout to a file, that wouldn't work at all.

    If you want to write to a stream, just open the stream and write to it.

    0 讨论(0)
  • 2021-01-02 22:15

    use ProcessStartInfo and Process classes and set RedirectStandardOutput to true, then you can capture the output from a stream.

    ProcessStartInfo info = new ProcessStartInfo("process.exe", "-arg1 -arg2");
    info.RedirectStandardOutput = true;
    Process p = Process.Start(info);
    p.Start();
    string output = p.StandardOutput.ReadToEnd();
    
    0 讨论(0)
  • 2021-01-02 22:26

    You can get a hold of the application's stdout by calling Console.OpenStandardOutput. From there, you can do whatever you want with the stream, although you won't be able to reassign it. If you want to do that you'll have to P/Invoke SetStdHandle and handle the details yourself.

    EDIT: Added example code for the P/Invoke route:

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetStdHandle(int nStdHandle, IntPtr nHandle);
    
    const int STD_OUTPUT_HANDLE = -11;
    
    static void RedirectStandardOutput(FileStream file)
    {
        SetStdHandle(STD_OUTPUT_HANDLE, file.SafeFileHandle.DangerousGetHandle());
    }
    
    0 讨论(0)
提交回复
热议问题