WP7 Development Tip of the Day: Checking for an internet connection

by brad 16. November 2010 16:46

The next two tips will come from the System.Net.NetworkInformation namespace.  This namespace has two classes that can be used to tell if your application has access to the internet and if that access changes.

If your application is going to use the data connection of the phone, it can be helpful to know when the data connection is available.  The NetworkInterface class makes this trivial.  Here’s a method you can drop right into your app to check for internet connectivity.

   1: private bool InternetIsAvailable()
   2: {
   3:     if (!NetworkInterface.GetIsNetworkAvailable())
   4:     {
   5:         MessageBox.Show("No internet connection is available.  Try again later.");
   6:         return false;
   7:     }
   8:     return true;
   9: }

As near as I could tell with some limited testing, the emulator will always report is has an internet connection, so you can use conditional DEBUG compilation if you want to test how things would work with no connection.

   1: private bool InternetIsAvailable()
   2: {
   3:     var available = !NetworkInterface.GetIsNetworkAvailable();
   4: #if DEBUG
   5:     available = false;
   6: #endif
   7:     if (!available)
   8:     {
   9:         MessageBox.Show("No internet connection is available.  Try again later.");
  10:         return false;
  11:     }
  12:     return true;
  13: }

Other Resources

More Tips

Tags:

Windows Phone | WP7 Tip of the Day

Comments

11/16/2010 5:10:41 PM #

pingback

Pingback from redleh360.wordpress.com

Weekend reading links. « Redleh360's Blog

redleh360.wordpress.com

11/17/2010 12:17:14 PM #

pingback

Pingback from topsy.com

Twitter Trackbacks for
        
        WP7 Development Tip of the Day: Checking for an internet connection
        [codebadger.com]
        on Topsy.com

topsy.com

11/18/2010 3:42:32 PM #

trackback

WP7 Development Tip of the Day: Detecting changes to the internet connection

WP7 Development Tip of the Day: Detecting changes to the internet connection

code badger

4/29/2012 11:28:30 PM #

pingback

Pingback from helderferreira.org

Weekend reading links – WP7 |

helderferreira.org

Comments are closed

About Brad

Brad Tutterow lives in Illinois and works in Missouri. He has 12 years of experience developing web sites and Windows applications using a variety of technologies and is most excited currently about Silverlight, Windows Phone 7, Halo Reach, and Visual Studio 2010.