控制台程序的RedirectStandardOutput

  string file = @"C:\Users\wtm30\source\repos\标准输出测试\ConsoleApp1\bin\Debug\ConsoleApp1.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.ReadToEnd();   //这一句会阻塞,只到程序退出(主动退出或被kill),所以上面的循环没有作用,如果用ReadLine的话则需要的循环
                if (string.IsNullOrEmpty(str) == false)
                {
                    this.sb.AppendLine(str);
                }
                System.Threading.Thread.Sleep(500);
            }
        }

猜你喜欢

转载自www.cnblogs.com/81/p/12619709.html