C#使用StandardOutput.ReadToEnd读取命令行出现卡死的解决办法

今天写一个C#程序,想调用CMD命令,并读取CMD的输出显示在文本框里,结果出现"卡死"现象,手动结束控制台程序就好了。逐步调试发现程序一直在StandardOutput.ReadToEnd();这里停止。
于是我在命令行发送输入信息后面加了一句StandardInput.Close();关闭输入然后再读取就好了


```csharp
在这里插入代码片
```public string 命令行_编译()  
        {
            string 运行目录 = get_exe(); //得到自己的运行目录 
           Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError =true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序
          // 
            //向cmd窗口发送输入信息

            p.StandardInput.WriteLine("cd " + 运行目录 + "\\rty");    //打开到rtt目录

            p.StandardInput.WriteLine(运行目录 + "\\Python27\\Sos.bat");
            p.StandardInput.Close();   //运行完毕关闭控制台输入
           add = p.StandardOutput.ReadToEnd(); //读取输出的信息

            p.Close();
            return add;
        }

发布了1 篇原创文章 · 获赞 0 · 访问量 1

猜你喜欢

转载自blog.csdn.net/qq_28308317/article/details/105447169