C# 操作CMD命令是否通过,解决p.StandardError.ReadToEnd()假死状态

      /// <summary>
        /// 检测CMD命令是否通过
        /// </summary>
        /// <param name="command">CMD命令</param>
        /// <returns></returns>
        public static bool CmdError(string command, out string msg)
        {
            bool flag = true;
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.AutoFlush = true;
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
            p.StandardInput.Close();  //要关闭,否则会造成假死状态
            msg = p.StandardError.ReadToEnd();
            if (!string.IsNullOrEmpty(msg))
            {
                flag = false;  //自定义Bool,如果为真则表示CMD命令出错
            }
            p.WaitForExit();
            p.Close();
            return flag;
        }

  

本文来自博客园,作者:云辰,转载请注明原文链接:https://www.cnblogs.com/yunchen/p/13630610.html

原文地址:https://www.cnblogs.com/yunchen/p/13630610.html