C# · 12月 31, 2021

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 720×480 \”{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)) { …. }}