asp.net check if url exists before opening popup

The following code (untested) should accomplish these tasks:

  1. Will verify that the url is defined
  2. Will ensure it beings with http:// or https://
  3. Will verify through an HttpRequest that the URL exists
  4. Will show either a popup window with the URL loaded, or a warning alert if the URL is undefined or doesn't exist.

Button click handler code:

string url = DocumentData.Tables[0].Rows[0]["WebAddress"].ToString();
string script;

if (!string.IsNullOrEmpty(url))
{
    // prepend http to url if it isn't there.
    if(!url.ToLower().StartsWith("http://") || !url.ToLower().StartsWith("https://"))
    {
        url = "http://" + url;
    }

    // verify URL exists:
    if (UrlExists(url))
    {
        script = "window.open('" + url  + "','_blank');";   
    }
    else
    {
        script = "alert('URL does not exist')";
    }
}
else
{
    script = "alert('No URL specified!')";
}

Page.ClientScript.RegisterStartupScript(this.GetType(), "WindowScript", script, true);

and define the following URL check method in your class:

public static bool UrlExists(string url)
{
   try
   {
      var request = WebRequest.Create(url) as HttpWebRequest;
      if (request == null) return false;
      request.Method = "HEAD";
      using (var response = (HttpWebResponse)request.GetResponse())
      {
         return response.StatusCode == HttpStatusCode.OK;
      }
   }
   catch (UriFormatException)
   {
      //Invalid Url
      return false;
   }
   catch (WebException)
   {
      //Unable to access url
      return false;
   }
}

I give full credit to the UrlExists method to: http://paigecsharp.blogspot.ca/2011/01/verify-url-exists.html