Loading

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;
        }

  

posted @ 2020-09-08 09:19  云辰  阅读(831)  评论(0编辑  收藏  举报