An url checker application is a program that checks a link to see if it works or if it's broken. Since the .Net Framework comes with classes that make connecting C# programs to the internet very simple, we can very easily write a website checker in C#...
You might remember from the downloading a file article that with C# you can connect to a URL and download the file. This includes html and php pages. Theoretically you could download the html code of a link and scan it for an error code, "File Not Found", "This page no longer exists...", etc.
But for the sake of simplicity let's avoid having to download the entire page. We can write an effective link checker by simply checking the URL address of the response page.
Setting up the web connection is simple:
Uri urlCheck = new Uri(url); WebRequest request = WebRequest.Create(urlCheck); request.Timeout = 15000;
The only trick is to format the string to a URL format and to specify a timeout duration, (15 seconds in our case). So far the application hasn't tried to connect to the link. To connect to the URL then add the following code segment:
WebResponse response; try { response = request.GetResponse(); } catch (Exception) { return false; //url does not exist }
The GetResponse command actually goes and tries to access the website. Right off the bat, if the request failed, then either the URL does not exist or the computer is not connected to the internet.
Otherwise the application found a webpage. Yet this could be a 404 error page telling you the link is broken. To check, compare the initial URL request (eg. www.site.com/page.html) with the actual response (which might be something like www.site.com/404.php).
If they match, then the application can officially declare the link working. Otherwise the page was redirected. If it was redirected you want to check the link of the redirected page.
If any of these strings are in the response-address then chances are there was an error: "400.php", "500.php", "400.htm", "500.html"
Note that you can customize this to check for more kinds of webpage errors. You could even choose to warn the user when the page was redirected at all.
Go ahead and download the C# source code. The CheckURL function takes in a webpage address as a parameter and returns a simple boolean value indicating whether the link is valid or broken...
Download URL Checker C# Source Code