C#中如何检查是否存在URL /是有效的? [英] C# How can I check if a URL exists/is valid?

查看:588
本文介绍了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
}

这篇关于C#中如何检查是否存在URL /是有效的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆