C#运行时获取进程输出

无论如何,重定向生成的进程的标准输出并将其捕获为它的发生。 我看到的所有内容在完成后都会执行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); } 

使用流程中的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)) { .... } } 

因此,经过一点挖掘,我发现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();