C#运行时获取进程输出

时间:2012-08-16 20:00:53

标签: c# process redirectstandardoutput

无论如何,重定向生成的进程的标准输出并将其捕获为正在发生的情况。我看到的所有内容在完成此过程后都会执行ReadToEnd。我希望能够在打印时获得输出。

编辑:

    private void ConvertToMPEG()
    {
        // Start the child process.
        Process p = new Process();
        // Redirect the output stream of the child process.
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        //Setup filename and arguments
        p.StartInfo.Arguments = String.Format("-y -i \"{0}\" -target ntsc-dvd -sameq -s 720x480 \"{1}\"", tempDir + "out.avi", tempDir + "out.mpg");
        p.StartInfo.FileName = "ffmpeg.exe";
        //Handle data received
        p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
        p.Start();
    }

    void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        Debug.WriteLine(e.Data);
    }

2 个答案:

答案 0 :(得分:14)

使用流程中的Process.OutputDataReceived事件来接收您需要的数据。

示例:

var myProc= new Process();

...            
myProc.StartInfo.RedirectStandardOutput = true;
myProc.OutputDataReceived += new DataReceivedEventHandler(MyProcOutputHandler);

...

private static void MyProcOutputHandler(object sendingProcess, 
            DataReceivedEventArgs outLine)
{
            // Collect the sort command output. 
    if (!String.IsNullOrEmpty(outLine.Data))
    {
      ....    
    }
}

答案 1 :(得分:3)

因此,经过多一点挖掘,我发现ffmpeg使用stderr进行输出。这是我修改后的代码来获取输出。

        Process p = new Process();

        p.StartInfo.UseShellExecute = false;

        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;

        p.StartInfo.Arguments = String.Format("-y -i \"{0}\" -target ntsc-dvd -sameq -s 720x480 \"{1}\"", tempDir + "out.avi", tempDir + "out.mpg");
        p.StartInfo.FileName = "ffmpeg.exe";

        p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
        p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);

        p.Start();

        p.BeginErrorReadLine();
        p.WaitForExit();