问题描述:
项目需要用cmd调用其它软件,实时获取软件处理结果,并根据获取到的结果决定下一步的输出,代码如下:
Process proCmd = null;
proCmd = new Process();
proCmd.StartInfo.FileName = "cmd.exe"; //cmd
proCmd.StartInfo.UseShellExecute = false; //不显示shell
proCmd.StartInfo.CreateNoWindow = true; //不创建窗口
proCmd.StartInfo.RedirectStandardInput = true; //打开流输入
proCmd.StartInfo.RedirectStandardOutput = true; //打开流输出
proCmd.StartInfo.RedirectStandardError = true; //打开错误流
proCmd.StandardInput.AutoFlush = true; //每次调用 Write()之后,将其缓冲区刷新到基础流
proCmd.OutputDataReceived += UpdateCmd;
proCmd.ErrorDataReceived += UpdateCmd;
proCmd.Start();//执行
proCmd.StandardInput.WriteLine(shell);
但是,Process的OutputDataReceived、ErrorDataReceived两个事件一直没有触发。
解决方法:
Process的OutputDataReceived、ErrorDataReceived两个事件只会异步读取操作过程中发生,需调用 Process的BeginErrorReadLine 、BeginOutputReadLine方法启动异步读取操作,执行命令的代码修改如下:
proCmd.Start();//执行
proCmd.BeginOutputReadLine();
proCmd.BeginErrorReadLine();
proCmd.StandardInput.WriteLine(shell);