2012-08-16 30 views
9

Có cách nào để chuyển hướng đầu ra tiêu chuẩn của quá trình sinh ra và nắm bắt nó khi nó xảy ra. Tất cả mọi thứ tôi đã thấy chỉ cần một ReadToEnd sau khi quá trình đã kết thúc. Tôi muốn có thể nhận được đầu ra khi nó đang được in.C# nhận được kết quả đầu ra của quá trình trong khi đang chạy

Edit:

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

Trả lời

13

Sử dụng Process.OutputDataReceived sự kiện từ quá trình này, để nhận dữ liệu bạn cần.

Ví dụ:

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

Có, và ngoài ra, bạn cần đặt 'RedirectStandardOutput' thành true để hoạt động. – vcsjones

+0

@vcsjones: chỉ cần in thêm bài đăng. – Tigran

+0

Như trong câu trả lời [ở đây] (http://stackoverflow.com/a/3642517/74757). –

3

Vì vậy, sau một chút đào hơn tôi phát hiện ra rằng ffmpeg sử dụng stderr cho đầu ra. Đây là mã được sửa đổi của tôi để có được đầu ra.

 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(); 
Các vấn đề liên quan