This article uses three methods to check whether a remote URL exists.
Private void page_load (Object sender, system. eventargs E)
{
String url1 = "http://dotnet.aspx.cc /";
String url2 = "http://dotnet.aspx.cc/Images/logo.gif ";
Response. Write ("<li> Method 1 :");
Response. Write (url1 + ":" + urlexistsusinghttpwebrequest (url1). tostring ());
Response. Write ("<li> Method 2 :");
Response. Write (url1 + "exist:" + urlexistsusingsockets (url1). tostring ());
Response. Write ("<li> method 3 :");
Response. Write (url1 + "exist:" + urlexistsusingxmlhttp (url1). tostring ());
Response. Write ("<li> Method 1 :");
Response. Write (url2 + ":" + urlexistsusinghttpwebrequest (url2). tostring ());
Response. Write ("<li> method 3 :");
Response. Write (url2 + "exist:" + urlexistsusingxmlhttp (url2). tostring ());
}
Private bool urlexistsusinghttpwebrequest (string URL)
{
Try
{
System. net. httpwebrequest myrequest = (system. net. httpwebrequest) system. net. webrequest. Create (URL );
Myrequest. method = "head ";
MySQL request. Timeout = 100;
System. net. httpwebresponse res = (system. net. httpwebresponse) myrequest. getresponse ();
Return (res. statuscode = system. net. httpstatuscode. OK );
}
Catch (system. net. webexception we)
{
System. Diagnostics. Trace. Write (We. Message );
Return false;
}
}
Private bool urlexistsusingxmlhttp (string URL)
{
// Note: msxml2.dll must be referenced in this method.
Msxml2.xmlhttp _ XMLHTTP = new msxml2.xmlhttpclass ();
_ XMLHTTP. Open ("head", URL, false, null, null );
_ XMLHTTP. Send ("");
Return (_ XMLHTTP. Status = 200 );
}
Private bool urlexistsusingsockets (string URL)
{
If (URL. startswith ("http: //") url = URL. Remove (0, "http: //". Length );
Try
{
System. net. iphostentry iphost = system. net. DNS. Resolve (URL );
Return true;
}
Catch (system. net. sockets. socketexception SE)
{
System. Diagnostics. Trace. Write (SE. Message );
Return false;
}
}