Checking for Network connectivity in Windows Phone 7 SDK

comments

In my early testing of Windows Phone 7 apps, it has become apparent that a lot of developers are simply not checking for network connectivity before attempting to access the internet – this gives a bad user experience as the user is left to wait until the connection times out. Checking to see if the device is connected to a network will improve this user experience dramatically.

imageThe Windows Phone SDK comes with some really nice, simple to use namespaces, one of these being the System.Net.NetworkInformation namespace.  This namespace has two classes that can be used to quickly tell if the device is connected to a network with the NetworkInterface class, and if that connection changes with the NetworkChange class.

If you are writing an application that uses the data connection on a device, it is usually best practice to check if there is an active data connection first to avoid any un-needed wait.

The NetworkInterface class is your friend when it comes to this as there is a single static Boolean that will tell you right away what state the devices network connection is in.

if (NetworkInterface.GetIsNetworkAvailable())
{
    // do stuff that talks to the interwebseses here...
}

Many people have reported that the emulator always reports an active internet connection – my personal experience shows that is always the case as well. If you want to test this, it might be best to add some build statements around your code to defensively check this when working in the emulator.

bool isConnected = NetworkInterface.GetIsNetworkAvailable();
#if DEBUG
isConnected = false;
#endif

if (isConnected)
{
    // do stuff that talks to the interwebseses here...
}