winform根据cmd获取网络ping值

来源:互联网 发布:火源计划激活码淘宝 编辑:程序博客网 时间:2024/05/16 05:52
 /// <summary>
        /// 测试网络连通性
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TestContinuity(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(TestUrltex.Text))
            {
                label10.Visible = true;//pinglabel
                label11.Visible = true;//pinglabel
                //获取ping值 时间=36ms
                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.WriteLine("ping -n 1 " + TestUrltex.Text);
                p.StandardInput.WriteLine("exit");
                string stre = p.StandardOutput.ReadToEnd();
                if (stre.IndexOf("(0%loss)") != -1)
                {
                    label11.ForeColor = System.Drawing.Color.LawnGreen;
                    label11.Text = "连接";
                }
                else if (stre.IndexOf("Destination host unreachable.") != -1 || stre.IndexOf("传输失败") > -1)
                {
                    label11.ForeColor = System.Drawing.Color.Red;
                    label11.Text = "无法达到目的的主机";
                }
                else if (stre.IndexOf("Request timed out.") != -1 || stre.IndexOf("请求超时") > -1)
                {
                    label11.ForeColor = System.Drawing.Color.Red;
                    label11.Text = "超时";
                }
                else if (stre.IndexOf("Unknown host") != -1)
                {
                    label11.ForeColor = System.Drawing.Color.Red;
                    label11.Text = "无法解析主机";
                }
                else if (stre.IndexOf("Ping 请求找不到主机") > -1)
                {
                    label11.ForeColor = System.Drawing.Color.Red;
                    label11.Text = "请求找不到主机";
                }
                else if (stre.IndexOf("往返行程的估计时间") > -1)
                {
                    label11.ForeColor = System.Drawing.Color.LawnGreen;
                    string ms = stre.Substring(stre.IndexOf("时间=") + 3, 3);
                    if (ms.Contains("m")) { ms = ms.Replace("m", ""); }
                    label11.Text = ms + "ms";
                }
                else
                {
                    label11.ForeColor = System.Drawing.Color.Red;
                    label11.Text = "未知错误";
                    Log("请检查‘网站路径’!");
                }
                p.Close();
            }
            else
            {
                label10.Visible = false;
                label11.Visible = false;
                Log("请输入‘网站路径’!");
            }
        }
原创粉丝点击