2

Is there any better way to check a Working Internet Connection than the following code because it always returns true, I don't know why.

bool isNetwork=NetworkInterface.GetIsNetworkAvailable();
if(!isNetwork)
{
   MessageBox.Show("Available.");
}
bytestorm
  • 1,411
  • 3
  • 20
  • 36
  • 2
    Well, first of all: network != internet. – SBI Nov 05 '13 at 11:02
  • 2
    Are you testing this through the emulator? Because for some reason, the emulator always reports an active connection. – Abbas Nov 05 '13 at 11:04
  • @SBI I read that thing before but it is not working also on the device(Lumia 610) – bytestorm Nov 05 '13 at 11:08
  • maybe you should look at this http://stackoverflow.com/questions/13617017/windows-phone-8-connection-handler-internet-availability – Schuere Nov 05 '13 at 11:39

2 Answers2

6

GetIsNetworkAvailable returns a result based on the network interfaces available. You should turn off all radios or turn on flight mode to get this to return false.

You may also want to check:

NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.None

In reality though, what you probably want to do is check if you can reach a specific URI. Just knowing if you can connect to "the internet" doesn't help you if there is a proxy between you and the endpoint that will block the connection or even if the server you're trying to reach is down or experiencing errors.

If you want to know if you can retrieve the data you desire from a specific endpoint, the only way to know for sure is to try. If you're successful then you can. If not there could be numerous reasons why.

Matt Lacey
  • 65,560
  • 11
  • 91
  • 143
  • I'd definitely emphasise the second part of this answer - just because some site/server/endpoint was available 10ns ago, does not imply that it's now reachable. And vice-versa. You have to write code to deal with *those* situations anyway - so why not *just* write the code that deals with it? – Damien_The_Unbeliever Nov 05 '13 at 14:45
  • @MATT great help, I understand now what was happening previously. I will give it a try. By the way, I would like to ask you another question. Is there any library function in C# that can do this task for me? – bytestorm Nov 05 '13 at 15:42
3

Try this also,

 public static bool CheckNetworkConnection()
    {
        var networkInterface = NetworkInterface.NetworkInterfaceType;

        bool isConnected = false;
        if ((networkInterface == NetworkInterfaceType.Wireless80211)||(networkInterface== NetworkInterfaceType.MobileBroadbandGsm)||(networkInterface==NetworkInterfaceType.MobileBroadbandCdma))
            isConnected = true;

        else if (networkInterface == NetworkInterfaceType.None)
            isConnected = false;
        return isConnected;
    }
Rashad Valliyengal
  • 3,132
  • 1
  • 25
  • 39