c# - How to check whether the URL is valid or not -
this question has answer here:
- c# how can check if url exists/is valid? 10 answers
i have 1 textbox in user enter url, if want check url while page rendering do?
here 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 code check whether url valid or not, can please tell me call this? {if want check https how can in code}
protected bool checkurlexists(string url) { // if url not contain http. add it. // if want check https how can do.this code http not https if (!url.contains("http://")) { url = "http://" + url; } try { var request = webrequest.create(url) httpwebrequest; request.method = "head"; using (var response = (httpwebresponse)request.getresponse()) { return response.statuscode == httpstatuscode.ok; } } catch { return false; } }
the textbox name urltxt
try below, 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 valid url"); } }
Comments
Post a Comment