While working on a Pocket PC app that will connect to a web service, I came across the need to test whether the device was able to connect to a URL before trying to do some work. Found this VB.NET code, and I whipped up a C# version ... customized it a tad of course.
public static bool TestUrl(string url)
{
return TestUrl(url,5000);
}
public static bool TestUrl(string url, int timeout)
{
HttpWebRequest req;
HttpWebResponse res;
try
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = timeout;
res = (HttpWebResponse)req.GetResponse();
req.Abort();
return (res.StatusCode == HttpStatusCode.OK);
}
catch
{
return false;
}
}
I added a timeout feature so that I wouldn't be left in the dark wondering when it would return false. The overload defaults the timeout to 5 seconds just for simplicity's sake. Also, I simplified the try/catch statement from the original ... no need to catch the webexception if you aren't going to do anything with it :-)