C# – Check if connected to internet
Posted on July 23rd, 2010 in C#, Tutorials | No Comments »
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.
Firstly, import System.Runtime.InteropServices namespace. Add this to the top of your code:
using System.Runtime.InteropServices;
Then use this code for checking connection state:
For C# Beginners: Add this code above or below public Form1() { … }
// API Method
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);
// A method for checking the state
public static bool IsConnected()
{
int Description;
return InternetGetConnectedState(out Description, 0);
}
Now you can use the above method to check for connection before doing anything that requires internet connection.
Example use:
// If internet connection is active
if (IsConnected())
{
// do something
}
else
{
MessageBox.Show("Please connect to the internet.");
If you have any questions please don’t hesitate to post a comment.