Monday, December 29, 2008

Check if the Internet Connection State is active inC#

A small application which uploads Images of new products and therefore I had to check if the Internet Connection State is active, otherwise it would crash. There are actually two ways (and probably more) of doing this, depending on your system. You could go with a direct api call:
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

//Creating a function that uses the API function...
public static bool IsConnectedToInternet()
{
int Desc;
return InternetGetConnectedState(out Desc, 0);
}
The Description can be found on MSDN, depending on the Connection the proper Value has to be entered.

Another way would be resolving some host of which you are sure it is online all the time. That could be microsoft.com, your company’s website or something else. Here we go:

public static bool IsConnected()
{
System.Uri Url = new System.Uri("http://www.microsoft.com");

System.Net.WebRequest WebReq;
System.Net.WebResponse Resp;
WebReq = System.Net.WebRequest.Create(Url);

try
{
Resp = WebReq.GetResponse();
Resp.Close();
WebReq = null;
return true;
}

catch
{
WebReq = null;
return false;
}
}

0 comments: