How to capture a Processes STDOUT and STDERR line by line as they occur, during process operation. (C#)

前端 未结 3 799
孤独总比滥情好
孤独总比滥情好 2020-12-20 11:56

I am going to execute a Process (lame.exe) to encode a WAV file to MP3.

I want to process the STDOUT and STDERR of the process to display progress information.

3条回答
  •  感情败类
    2020-12-20 12:20

    If running via the Process class, you can redirect the streams so you may process them. You can read from stdout or stderr synchronously or asynchronously. To enable redirecting, set the appropriate redirection properties to true for the streams you want to redirect (e.g., RedirectStandardOutput) and set UseShellExecute to false. Then you can just start the process and read from the streams. You can also feed input redirecting stdin.

    e.g., Process and print whatever the process writes to stdout synchronously

    var proc = new Process()
    {
        StartInfo = new ProcessStartInfo(@"SomeProcess.exe")
        {
            RedirectStandardOutput = true,
            UseShellExecute = false,
        }
    };
    if (!proc.Start())
    {
        // handle error
    }
    var stdout = proc.StandardOutput;
    string line;
    while ((line = stdout.ReadLine()) != null)
    {
        // process and print
        Process(line);
        Console.WriteLine(line);
    }
    

提交回复
热议问题