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

前端 未结 5 881
感情败类
感情败类 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 12:52

    I simply used Fredrik Mörk answer above but placed it within a method:

    private bool checkURL(string url)
            {
                bool pageExists = false;
                try
                {
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.Method = WebRequestMethods.Http.Head;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    pageExists = response.StatusCode == HttpStatusCode.OK;
                }
                catch (Exception e)
                {
                    //Do what ever you want when its no working...
                    //Response.Write( e.ToString());
                }
                return pageExists;
            }
    

提交回复
热议问题