I am making a simple program in visual c# 2005 that looks up a stock symbol on Yahoo! Finance, downloads the historical data, and then plots the price history for the specified ticker symbol.
I know the exact URL that I need to acquire the data, and if the user inputs an existing ticker symbol (or at least one with data on Yahoo! Finance) it works perfectly fine. However, I have a run-time error if the user makes up a ticker symbol, as the program tries to pull data from a non-existent web page.
I am using the WebClient class, and using the DownloadString function. I looked through all the other member functions of the WebClient class, but didn't see anything I could use to test a URL.
How can I do this?
These solutions are pretty good, but they are forgetting that there may be other status codes than 200 OK. This is a solution that I've used on production environments for status monitoring and such.
If there is a url redirect or some other condition on the target page, the return will be true using this method. Also, GetResponse() will throw an exception and hence you will not get a StatusCode for it. You need to trap the exception and check for a ProtocolError.
Any 400 or 500 status code will return false. All others return true. This code is easily modified to suit your needs for specific status codes.
Following on from the examples already given, I'd say, it's best practice to also wrap the response in a using like this
I have always found Exceptions are much slower to be handled.
Perhaps a less intensive way would yeild a better, faster, result?
Then just use:
i have a more simple way to determine weather a url is valid.
Here is another option
If I understand your question correctly, you could use a small method like this to give you the results of your URL test:
You could wrap the above code in a method and use it to perform validation. I hope this answers the question you were asking.