C#调用外部dos命令并取得返回結果

private static string CmdPing(string strIp)
         {

             Process p
= new Process();
            
//设定程序名
             p.StartInfo.FileName = "cmd.exe";
            
//关闭Shell的使用
             p.StartInfo.UseShellExecute = false;
            
//重定向标准输入
             p.StartInfo.RedirectStandardInput = true;
            
//重定向标准输出
             p.StartInfo.RedirectStandardOutput = true;
            
//重定向错误输出
             p.StartInfo.RedirectStandardError = true;
            
//设置不显示窗口
             p.StartInfo.CreateNoWindow = true;

            
string pingrst;
            
//启动进程
             p.Start();
            
//输入要执行的命令,这里就是ping
             p.StandardInput.WriteLine("ping -n 1 " + strIp);
             p.StandardInput.WriteLine(
"exit");
            
//从输出流获取命令执行结果
            string strRst = p.StandardOutput.ReadToEnd();

            
//分析strRst字符串就可以知道网络的连接情况
            if (strRst.IndexOf("(0% loss)") != -1)
                 pingrst
= "连接";
            
else if (strRst.IndexOf("Destination host unreachable.") != -1)
                 pingrst
= "无法到达目的主机";
            
else if (strRst.IndexOf("Request timed out.") != -1)
                 pingrst
= "超时";
            
else if (strRst.IndexOf("Unknown host") != -1)
                 pingrst
= "无法解析主机";
            
else
                 pingrst
= strRst;

             p.Close();

            
return pingrst;

         }




文章来自: alocne
引用通告: 查看所有引用 | 我要引用此文章
Tags:
评论: 0 | 引用: 0 | 查看次数: 2740
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭