winform根據cmd獲取網絡ping值

 ///
        /// 測試網絡連通性
        /// </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("請輸入‘網站路徑’!");
            }
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章