2012-08-16 15 views
9

¿Hay alguna forma de redirigir la salida estándar de un proceso engendrado y capturarlo mientras está sucediendo? Todo lo que he visto solo hace un ReadTo End después de que el proceso haya terminado. Me gustaría poder obtener el resultado mientras se está imprimiendo.C# get process output while running

Editar:

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

Respuesta

13

Uso Process.OutputDataReceived evento del proceso, para recibir los datos que necesita.

Ejemplo:

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

Sí, y además necesita establecer 'RedirectStandardOutput' en true para que esto funcione. – vcsjones

+0

@vcsjones: solo se está escribiendo una publicación adicional. – Tigran

+0

Como en la respuesta [aquí] (http://stackoverflow.com/a/3642517/74757). –

3

Así que después de un poco más de excavación descubrí que utiliza ffmpeg para la salida stderr. Aquí está mi código modificado para obtener el resultado.

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