Check whether the remote URL exists

Source: Internet
Author: User
Tags dotnet

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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.