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