Wednesday, November 18, 2009

Check for valid Internet Connection using C#

on many application we need internet connectio , such as smart client to send receive the data, now in this case below code will help you to make sure that you have proper internet connection or not , the conecpt is like very simple, at first we simply check that if the user has network connection and according to that it will return Success / Fail message.

Now i just ping the two website (www.google.com ,www.yahoo.com) which will ping that site and return fail or success message.


C#
public bool GetIsConnAvail()
{
var success = false;
string StatusMsg;
if (NetworkInterface.GetIsNetworkAvailable() == false)
{
return success;
}
string[] Mysite = { "www.google.com", "www.yahoo.com"};
try
{
using (var ping = new Ping())
{
foreach (var url in Mysite)
{
var replyMsg = ping.Send(url, 300);
if (replyMsg.Status == IPStatus.Success)
{
success = true;
StatusMsg = "Connection Found..."
break;
}
else
{
StatusMsg = "Internet Connection not Found on your machine..."
}

}
}
}

catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
return success;
}



i thing this code will surely help you to search your connection faster than other ways.

No comments:

Post a Comment