2012-08-16 24 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(); 
相關問題