Process类重定向输出时如何实现逐行输出。
比如使用Process类调用CMD执行一个PING命令。
总是要等到命令完成后才能输出结果。
如何才能做到像在CMD下执行命令那样,逐行的输出。
假如有一个外部程序执行的时间很长。
要是等程序执行完毕后才能得到输出结果。
那要如何得知外部程序现在执行的进度?

解决方案 »

  1.   

    重定向输出即可:Process p = new Process();
    // Redirect the output stream of the child process.
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.FileName = "myprog.exe";
    p.Start();
    do{
      string output = p.StandardOutput.ReadLine();
      // process this line...
    }while(output != null);
    // Wait for child process to finish
    p.WaitForExit();至于如果得到Process的执行进度是不能完全控制的,除非你调用自己写的程序并且有自己的一个IPC通讯机制(比如通过File Mapping共享一些数据)。
      

  2.   

    哦,如果需要异步处理,可以考虑Process.BeginOutputReadLine,请自己查看MSDN例子。.NET Framework 1.X版本就需要自己创建线程来处理了。
      

  3.   

    感谢楼上的各位。
    用Process.BeginOutputReadLine就可以实现~