Since many applications (like Smart Clients) use the internet to send/ retrieve data, it's a good thing to check to make sure the user has access to the internet before making your call. This will prevent connection exceptions. The code below first checks to make sure the user even has a network connection, then tries to ping up to three web sites to see if the ping is successful (of course you can change the sites to your linking or add more). The good thing that this code does that most other code I saw when researching this, is that it does not rely on an exception to determine that an internet connection is not available. Therefor it's much faster!

C#

public bool GetIsInternetConnectionAvailable()

{

   var success = false;

 

   if (NetworkInterface.GetIsNetworkAvailable() == false)

   {

      return success;

   }

 

   string[] sitesList = { "www.google.com", "www.microsoft.com", "www.mycompany.com" };

 

   try

   {

      using (var ping = new Ping())

      {

         foreach (var url in sitesList)

         {

            var reply = ping.Send(url, 300);

 

            if (reply.Status == IPStatus.Success)

            {

               success = true;

               break;

            }

         }

      }

   }

   catch (Exception ex)

   {

      Trace.WriteLine(ex.Message);

   }

 

   return success;

}


VB.NET

Public Function GetIsInternetConnectionAvailable() As Boolean

   Dim success = False

 

   If My.Computer.Network.IsAvailable = False Then

      Return success

   End If

 

   Dim sitesList As String() = {"www.google.com", "www.microsoft.com", "www.mycompany.com"}

 

   Try

      For Each url In sitesList

         If My.Computer.Network.Ping(url, 300) Then

            success = True

            Exit For

         End If

      Next

   Catch ex As Exception

      Trace.WriteLine(ex.Message)

   End Try

 

   Return success

End Function


Tip By: David McCarter