C# 在运行时获取进程输出

标签 c# process redirectstandardoutput

是否有重定向生成进程的标准输出并在其发生时捕获它的方法。我所看到的一切都在该过程完成后执行 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 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);
    }

最佳答案

使用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))
    {
      ....    
    }
}

关于C# 在运行时获取进程输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11994610/

相关文章:

c# - 仅从参数数组调用某些值的总和

c# - RedirectStandardOutput 和批处理文件中的暂停命令

c# - 从文件路径获取字符串而不是路径格式

C#。如何将一维数组转换为二维数组

Python 循环延迟

vb.net - 需要帮助将 Vb.Net 转换为 Delphi (API Stuff (?))

java - 是否可以将 Java 中的标准输出设置为文件和标准输出?

c# - 如何识别流程是否需要输入?

c# - 用于编译的 .NET 绑定(bind)重定向

c# - 如何处理文件名