C#中如何检查是否存在URL /是有效的?
我在Visual C#2005中查找在雅虎财经股票代码,下载历史数据,然后绘制指定的股票代码历史价格制作一个简单的程序。
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.
我使用WebClient类,并使用DownloadString功能。我经历了所有WebClient类的其他成员函数看了看,但没有看到任何东西,我可以用它来测试一个URL。
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?
您可以发出一个的HEAD要求,而不是GET?
You could issue a "HEAD" request rather than a "GET"?
(编辑) - 哈哈!貌似我这样做以前也!;改为维基避免REP-赢得的指责。因此,为了测试一个URL,而无需下载内容的成本:
(edit) - lol! Looks like I've done this before!; changed to wiki to avoid accusations of rep-garnering. So to test a URL without the cost of downloading the content:
// using MyClient from linked post
using(var client = new MyClient()) {
client.HeadOnly = true;
// fine, no content downloaded
string s1 = client.DownloadString("http://google.com");
// throws 404
string s2 = client.DownloadString("http://google.com/silly");
}
您会尝试
/ 抓
围绕 DownloadString
来检查错误;没有错误?它的存在...
You would try
/catch
around the DownloadString
to check for errors; no error? It exists...
使用C#2.0(VS2005):
With C# 2.0 (VS2005):
private bool headOnly;
public bool HeadOnly {
get {return headOnly;}
set {headOnly = value;}
}
和
using(WebClient client = new MyClient())
{
// code as before
}