Windows 8: IsConnectedToInternet?


In writing my own app, I found myself wondering, “how to I detect if the machine is actually connected to the internet before I start making all manner of web services calls?”. Well, below is my solution written in C#. Enjoy!

 

Code:

private bool IsConnectedToInternet()
{
    bool connected = false;

    ConnectionProfile cp = NetworkInformation.GetInternetConnectionProfile();

    if (cp != null)
    {
        NetworkConnectivityLevel cl = cp.GetNetworkConnectivityLevel();

        connected = cl == NetworkConnectivityLevel.InternetAccess;
    }

    return connected;
}

 

Usage:

if(!IsConnectedToInternet())
{
     //some kind of error handling here
}
else
{
     //we're good to go, so do something with it!
}

If you find a better way of doing it, please let me know in the comments.

Comments (2)

  1. It Works!!! says:

    Great man, MSDN does not give support for this

    thanks a lot

  2. tomdjpn says:

    but this fails if the user is connected to internet through a VPN.

    See:

    quawp.azurewebsites.net/…/checking-connectivity-the-correct-way

    and many threads that seem related to this issue, e.g.

    social.technet.microsoft.com/…/96a7f1ab-1a24-48af-a6ec-6988c116be91