How to check whether the URL is valid or not

asp.net, c#

Solution

Try like below, It will help you....

     protected void btnRender_Click(object sender, EventArgs e)
        {
            if(CheckUrlExists(urltxt.Text))
            {
                string strResult = string.Empty;
                WebResponse objResponse;
                WebRequest objRequest = System.Net.HttpWebRequest.Create(urltxt.Text);
                objResponse = objRequest.GetResponse();
                using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
                {
                    strResult = sr.ReadToEnd();
                    sr.Close();
                }
                strResult = strResult.Replace("<form id='form1' method='post' action=''>", "");
                strResult = strResult.Replace("</form>", "");
                TextBox1.Text = strResult.Trim();
                div.InnerHtml = strResult.Trim();
            }
            else
            {
                MessageBox.Show("Not a Valid URL");
            }
        }

Problem

I have one textbox in that user enter the URL, but if want to check that URL while page rendering then what to do? Here is my code: ``` protected void btnRender_Click(object sender, EventArgs e) { string strResult = string.Empty; WebResponse objResponse; WebRequest objRequest = System.Net.HttpWebRequest.Create(urltxt.Text); objResponse = objRequest.GetResponse(); using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) { strResult = sr.ReadToEnd(); sr.Close(); } strResult = strResult.Replace("<form id='form1' method='post' action=''>", ""); strResult = strResult.Replace("</form>", ""); TextBox1.Text = strResult.Trim(); div.InnerHtml = strResult.Trim(); } ``` I have this code to check whether URL is valid or not, so can you please tell me where to call this? {if i want to also check https also then how can i do in this code} ``` protected bool CheckUrlExists(string url) { // If the url does not contain Http. Add it. // if i want to also check for https how can i do.this code is only for http not https if (!url.Contains("http://")) { url = "http://" + url; } try { var request = WebRequest.Create(url) as HttpWebRequest; request.Method = "HEAD"; using (var response = (HttpWebResponse)request.GetResponse()) { return response.StatusCode == HttpStatusCode.OK; } } catch { return false; } } ``` The TextBox name is urltxt

Original source

Related problems