C# – Check if connected to internet

I was working on an application which checked for updates. I used WebRequest/WebResponse for checking updates. It showed a continuous Progressbar while checking for updates. But there was a problem. It worked properly when you were connected to internet but it  just showed the progressbar all the time if not connected.

The solution for that was to check for internet connection before checking for updates. If connected then check for updates otherwise show an error.

Checking for the state of internet connection is very simple. Let’s get started.

Firstly, import System.Runtime.InteropServices namespace. Add this to the top of your code:

Then use this code for checking connection state:

For C# Beginners: Add this code above or below public Form1() { … }

Now you can use the above method to check for connection before doing anything that requires internet connection.

Example use:

If you have any questions please don’t hesitate to post a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *