在c#中使用ping

当我用Windows来Ping一个远程系统时,它说没有回复,但是当我用C#ping时,它说成功了。 Windows是正确的,设备没有连接。 为什么我的代码能够在Windows不成功时ping?

这是我的代码:

Ping p1 = new Ping(); PingReply PR = p1.Send("192.168.2.18"); // check when the ping is not success while (!PR.Status.ToString().Equals("Success")) { Console.WriteLine(PR.Status.ToString()); PR = p1.Send("192.168.2.18"); } // check after the ping is n success while (PR.Status.ToString().Equals("Success")) { Console.WriteLine(PR.Status.ToString()); PR = p1.Send("192.168.2.18"); } 
 using System.Net.NetworkInformation; public static bool PingHost(string nameOrAddress) { bool pingable = false; Ping pinger = new Ping(); try { PingReply reply = pinger.Send(nameOrAddress); pingable = reply.Status == IPStatus.Success; } catch (PingException) { // Discard PingExceptions and return false; } return pingable; } 
 using System.Net.NetworkInformation; namespace PingTest1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Ping p = new Ping(); PingReply r; string s; s = textBox1.Text; r = p.Send(s); if (r.Status == IPStatus.Success) { lblResult.Text = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " Successful" + " Response delay = " + r.RoundtripTime.ToString() + " ms" + "\n"; } } private void textBox1_Validated(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == "") { MessageBox.Show("Please use valid IP or web address!!"); } } } } 

在我的情况下,如果“启用Visual Studio宿主进程”(位置是== >>项目 – >属性 – >debugging)禁用,ping方法可能无法正常工作。 请尝试!

 private void button26_Click(object sender, EventArgs e) { System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo(); proc.FileName = @"C:\windows\system32\cmd.exe"; proc.Arguments = "/c ping -t " + tx1.Text + " "; System.Diagnostics.Process.Start(proc); tx1.Focus(); } private void button27_Click(object sender, EventArgs e) { System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo(); proc.FileName = @"C:\windows\system32\cmd.exe"; proc.Arguments = "/c ping " + tx2.Text + " "; System.Diagnostics.Process.Start(proc); tx2.Focus(); }