I am building a C# windows form app that pings multiple computers by name, which the user can specify.
I am using the System.Net.NetworkInformation.Ping class and the SendAsync method, with a method to handle the result.
The issue I am having occurs when the user specifies a computer name which does not exist. Rather than Ping returning an error to my callback method, however, I get a TargetInvocationException at Application.Run(new Form()) (the main method of the entire form). I have tried surrounding relevant code with try/catch but they never seem to catch the exception
Here is relevant code for ping:
Ping p = null;
try
{
p = new Ping();
p.PingCompleted += new PingCompletedEventHandler (updateUI);
p.SendAsync(computername, 10, computername);
}
catch (Exception)
{
((IDisposable)p).Dispose();
MessageBox.Show("Ping Failed...");
}
Check the e.Error property first in your PingCompleted event handler. Trying to use the other properties when it is not null is a guaranteed kaboom. From the PingCompletedEventArgs.Error property documentation in MSDN: