George Loveless

George Loveless

  • NA
  • 3
  • 10.6k

how to validate a URL in c#

Sep 29 2010 6:15 PM

  Hi, I need to write a tool that will report broken URL's.    The URL should only reports broken if the user see's a 404 Error in the browser.  I believe there might be tricks to handle web servers that do URL re-writing.   Here's what I have.   As you can see only some URL validate incorrectly.  Thanks you for any help.
           
  string url = "";

            // TEST CASES 
            url = "http://newsroom.lds.org/ldsnewsroom/eng/news-releases-stories/local-churches-teach-how-to-plan-for-disasters"; //Prints "BROKEN", although this is getting re-written to good url below. //url = "http://beta-newsroom.lds.org/article/local-churches-teach-how-to-plan-for-disasters"; // Prints "GOOD" //url = "http://"; //Prints "BROKEN" //url = "google.com"; //Prints "BROKEN" althought this should be good. //url = "www.google.com"; //Prints "BROKEN" althought this should be good. //url = "http://www.google.com"; //Prints "GOOD" try { if (url != "") { WebRequest Irequest = WebRequest.Create(url); WebResponse Iresponse = Irequest.GetResponse(); if (Iresponse != null) { _txbl.Text = "GOOD"; } } } catch (Exception ex) { _txbl.Text = "BROKEN"; }

 

 

Answers (3)