Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to check if a web url exists, using asp.net?

how to use below snippet accurately?

C++
public bool urlExists(string url)
{
   HttpWebRequest req  = (HttpWebRequest)WebRequest.Create(url);
   req.AllowRedirect = false;
   HttpWebResponse res = (HttpWebResponse)req.GetResponse();

   //How to check if url exists - code??

   if(/*exists code*/)
      return true;
   else
      return false;
} 
Posted
Updated 16-Sep-11 9:04am
v3

Check the HttpStatus. It is a property of the Response object.

Best Regards,

MRB
 
Share this answer
 
Hi,

I tried some code it works perfect If there is url it shows results otherwise
shows msgs.

C#
   WebRequest req = WebRequest.Create("http://www.codeproject.com");
        WebResponse res;
        try
        {
           res = req.GetResponse();
        }
        catch (Exception ed)
        {
            goto sd;
        }
        Stream sg  = res.GetResponseStream();
     
        StreamReader sr = new StreamReader(sg);
        resdiv.InnerHtml = sr.ReadToEnd();
goto fg;
    sd:
        resdiv.InnerHtml = "Sorry no such url exists ";
        ;  
fg:;



The meaning of above code is if url has exists there is no exeception if it not exists it'll raise webnull Execption.

We handle that execption in that we write what we've to do if url not exists.


I hope you'll understand what i said.


All the best
 
Share this answer
 
v2
Hello,

You can check the web url is exist or not on following url.

public bool urlExists(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.AllowAutoRedirect = false;
HttpWebResponse res = (HttpWebResponse)req.GetResponse();

if (res.StatusCode == HttpStatusCode.OK)
return true;
else
return false;
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900