一个调用系统自带的Cmd的例子,可实现ping和ipconfig操作 /// <summary>
 /// <summary>
        /// 执行CMD语句
        /// </summary>
        /// <param name="cmd">要执行的CMD命令</param>
        public string RunCmd(string cmd)
        {
            proc.StartInfo.CreateNoWindow = true;
            //设定程序名
            proc.StartInfo.FileName = "cmd.exe";
            //关闭Shell的使用,要重定向 IO 流,Process 对象必须将 UseShellExecute 属性设置为 False。
            proc.StartInfo.UseShellExecute = false;
            //重定向错误输出
            proc.StartInfo.RedirectStandardError = true;
            //重定向标准输入
            proc.StartInfo.RedirectStandardInput = true;
            //重定向标准输出
            proc.StartInfo.RedirectStandardOutput = true;
            string pingStr;
            //启动
            proc.Start();
            //输入执行命令
            proc.StandardInput.WriteLine("ping "  cmd);
            proc.StandardInput.WriteLine("exit");
            //从输出流获取结果
            string outStr = proc.StandardOutput.ReadToEnd();
            if (outStr.IndexOf("(0% loss)") != -1)
                pingStr = "链接";
            else if (outStr.IndexOf("Destination host unreachable.") != -1)
                pingStr = "无法到达主机";
            else if (outStr.IndexOf("Request timed out.") != -1)
                pingStr = "超时";
            else if (outStr.IndexOf("Unkonw host") != -1)
                pingStr = "无法解析主机";
            else
                pingStr = outStr;
            proc.Close();
            return pingStr;
        }
        /// <summary>
        /// 查询显示ipconfig的所有信息
        /// </summary>
        /// <returns></returns>
        public string GetIp()
        {
            //设置不显示窗口
            proc.StartInfo.CreateNoWindow = true;
            //设定程序名
            proc.StartInfo.FileName = "cmd.exe";
            //关闭Shell的使用,要重定向 IO 流,Process 对象必须将 UseShellExecute 属性设置为 False。
            proc.StartInfo.UseShellExecute = false;
            //重定向错误输出
            proc.StartInfo.RedirectStandardError = true;
            //重定向标准输入
            proc.StartInfo.RedirectStandardInput = true;
            //重定向标准输出
            proc.StartInfo.RedirectStandardOutput = true;
            //启动
            proc.Start();
            //输入执行命令
            proc.StandardInput.WriteLine("ipconfig /all\r\n");
            proc.StandardInput.WriteLine("exit");
            // 从输出流获取结果
            string outStr = proc.StandardOutput.ReadToEnd();
            proc.Close();
            return outStr;
        }

 
  
					
				
评论