Is there a faster way to check if an external web page exists?

前端 未结 5 870
感情败类
感情败类 2021-02-07 12:23

I wrote this method to check if a page exists or not:

protected bool PageExists(string url)
{
try
    {
        Uri u = new Uri(url);
        WebRequest w = WebR         


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 13:08

    I think your approach is rather good, but would change it into only downloading the headers by adding w.Method = WebRequestMethods.Http.Head; before calling GetResponse.

    This could do it:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
    request.Method = WebRequestMethods.Http.Head;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    bool pageExists = response.StatusCode == HttpStatusCode.OK;
    

    You may probably want to check for other status codes as well.

提交回复
热议问题