I wrote 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;
}
}
Include one of those functions in your code and you’re set!
14 comments ↓
Good one
Very GOOD!
Thanks. nice one
very very nice
does not seem to work on Silverlight…
GOOD!! Thx 🙂
Thanx dude. I was looking for last week to solve this problem finally come over this solutions. and worked. thanx
Thank you
Nice one!
very Good
But can control(on and off)the internet using c# or java
Hello ,
Your coding is very helpful to me dear…….
Thanks a lot……..
Simple and genial.. thanks
Thanks! Simple and easy to use.
Hi….
Thanks a lot….
Its very usefull to me… Simple & easy to use….
Leave a Comment