控制台程序的RedirectStandardOutput

  string file = @"C:Userswtm30source epos标准输出测试ConsoleApp1inDebugConsoleApp1.exe";
            ProcessStartInfo pi = new ProcessStartInfo(file, "");
            pi.UseShellExecute = false;
            pi.RedirectStandardOutput = true;
            pi.RedirectStandardInput = true;

             // pi.WindowStyle = ProcessWindowStyle.Hidden; //窗口隐藏?好像这一句没有用
            pi.CreateNoWindow = true;   //是否显示调用窗口

              p = Process.Start(pi);

            Task.Run(() =>
            {
                接收输出信息(p);
            });

  private void 接收输出信息(  Process p)
        {
           
            while (this.停止 == false)
            {
                string str = p.StandardOutput.ReadLine();
                if (str == null)
                {
                    break; //程序已退出
                }

                this.sb.AppendLine(str);


                System.Threading.Thread.Sleep(500);
            }


            //while (this.停止 == false)
         //   {
          //      string str = p.StandardOutput.ReadToEnd();   //这一句会阻塞,只到程序退出(主动退出或被kill),所以上面的循环没有作用,如果用ReadLine的话则需要的循环
          //      if (string.IsNullOrEmpty(str) == false)
           //     {
          //          this.sb.AppendLine(str);
            //    }
           //     System.Threading.Thread.Sleep(500);
         //   }
        }

原文地址:https://www.cnblogs.com/81/p/12619709.html