小编典典

C#如何检查URL是否存在/有效?

c#

我正在Visual C#2005中编写一个简单的程序,该程序在Yahoo!上查找股票代码。财务,下载历史数据,然后绘制指定股票代码的价格历史。

我知道我需要获取数据的确切URL,并且如果用户输入了现有的股票代号(或至少一个带有Yahoo!
Finance上的数据的代号),它就可以很好地工作。但是,如果用户编写了股票代码,则会出现运行时错误,因为该程序试图从不存在的网页中提取数据。

我正在使用WebClient类,并使用DownloadString函数。我浏览了WebClient类的所有其他成员函数,但没有看到可用于测试URL的任何内容。

我怎样才能做到这一点?


阅读 394

收藏
2020-05-19

共1个答案

小编典典

您可以发出
HEAD”
请求而不是“
GET”请求?

(编辑)-大声笑!看来我以前做过!改为Wiki,以避免指责获得销售代表。因此,要测试URL而无需下载内容:

// 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");
}

您将try/ catch在附近DownloadString检查错误;没有错吗 存在…


使用C#2.0(VS2005):

private bool headOnly;
public bool HeadOnly {
    get {return headOnly;}
    set {headOnly = value;}
}

using(WebClient client = new MyClient())
{
    // code as before
}
2020-05-19