Welcome to NeoTekSystems Blog Sign in | Join | Help

Checking for an internet connection C# .NET Compact

If you or your company writes any Pocket PC software using the .NET Compact framework that consumes webservices you will deffinately need to check for an internet connection. This way you can warn the end user that if he/she wants your software to display the most up to date data from a webservice an internet connection is needed. I shoved the example below in a static class so I could call on it whenever a data retrieval was requested. The code is as follows.

using System;
using System.Net;

namespace InternetConnectionCheckExample
{
 /// <summary>
 /// Summary description for CheckConnection.
 /// </summary>
 public class CheckConnection
 {
  public static bool Once(string targetAddress) // I passed www.google.com in as it is very reliable.
  {
   HttpWebRequest request;
   HttpWebResponse response;
   bool isConnected = false;

   try
   {
    request = (HttpWebRequest)WebRequest.Create(targetAddress);
    response = (HttpWebResponse)request.GetResponse();
    request.Abort();

    // success?
    if(response.StatusCode == HttpStatusCode.OK)
    {
     isConnected = true;
    }
   }
   catch(WebException we)
   {
    string errMsg = we.Message;
    isConnected = false;
   }
   catch(Exception ex)
   {
    string errMsg = ex.Message;
    isConnected = false;
   }
   finally
   {
    request = null;
    response = null;
   }
   return isConnected;
  }
 }
}

It is as simple as that. Call it from your form and check if it returns true or false. true = connected false = not connected.

Later,

Published Monday, June 13, 2005 1:15 AM by bparker

Comments

No Comments

Anonymous comments are disabled