I have a method that loops ping requests, and I’d like when I click Ctrl+c, it break the loop and give me statics like the normal cmd, but when I click Ctrl+c, I get
Press Any Key To Continue… <<
and then program closes .
For example : ping google.com -t << that will ping google with endless loop, but I need to break the loop ONLY when I click Ctrl+c
private void _t(string website)
{
Ping pingSender = new Ping();
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 10000;
try
{
PingOptions options = new PingOptions(64, false);
PingReply send0 = pingSender.Send(website, timeout, buffer, options);
Console.WriteLine("\nPinging {0} [{1}] With {2} bytes of data :", website, send0.Address.ToString(), send0.Buffer.Length);
while (1 < 2)
{
PingReply reply = pingSender.Send(website, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime / 5, reply.Options.Ttl);
}
else
{
Console.WriteLine("Request timed out.");
}
}
}
catch
{
Console.WriteLine("Ping request could not find host {0} ", website + ".Please check the name and try again.");
}
}
But instead of using while (1<2), I want to use something like :
while (ConsoleKeyInfo.Equals("Control + c") not clicked) // sure it is wrong , but that`s what I wanna achieve
{
PingReply reply = pingSender.Send(website, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("Reply from {0}: Bytes {1} time={2} TTL={3}", reply.Address.ToString(), reply.Buffer.Length, reply.RoundtripTime / 5, reply.Options.Ttl);
}
else
{
Console.WriteLine("Request timed out.");
}
}
There is a fairly complete tutorial (with code) here. I did a quick test and their example actually worked (imagine that).
Here is their code: