2012-08-16 23 views
9

是否有重定向衍生进程的标准输出并捕获它的发生。在过程完成后,我所看到的所有内容都会执行ReadToEnd。我希望能够在打印时获得输出。C#在运行时获取进程输出

编辑:

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); 
    } 

回答

13

使用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

是的,此外,您需要将'RedirectStandardOutput'设置为true才能工作。 – vcsjones 2012-08-16 20:05:07

+0

@vcsjones:只需要额外的贴子。 – Tigran 2012-08-16 20:05:25

+0

在答案[在这里](http://stackoverflow.com/a/3642517/74757)。 – 2012-08-16 20:06:04

3

所以多一点挖后,我发现ffmpeg的使用标准错误输出。这里是我修改的代码来获取输出。

 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(); 
相关问题