导航

C#使用命令行方式实现Ping简单功能

Posted on 2007-06-28 10:34  无心放纵  阅读(596)  评论(0)    收藏  举报

using System.Diagnostics;
.......
private string CmdPing(string strIP)
  {
   string pingRst;
   Process p = new Process();
   p.StartInfo.FileName="cmd.exe";
   p.StartInfo.UseShellExecute=false;
   p.StartInfo.RedirectStandardError=true;
   p.StartInfo.RedirectStandardInput=true;
   p.StartInfo.RedirectStandardOutput=true;
   p.StartInfo.CreateNoWindow=true;      //不显示命令行窗口

   p.Start();
   p.StandardInput.WriteLine("ping -n 1 "+strIP);    //输入要运行的命令
   p.StandardInput.WriteLine("exit");
   string strRst=p.StandardOutput.ReadToEnd();    //取得输出结果
   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("Unknow host")!=-1) pingRst="无法解析主机";
   else pingRst=strRst;
   p.Close();
   return pingRst;
  }