取消错误“主机名无法解析”

时间:2011-06-19 15:19:40

标签: c#

这是我的代码:

string Url = "http://illution.dk/";
WebClient Http = new WebClient();
Http.DownloadStringAsync(new Uri(Url));
Http.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetModelTypeResponse);

如果我在没有互联网连接的计算机上运行此操作,则会引发错误。 “主机名无法解析”

有什么办法可以删除此错误消息吗?或者检查是否没有互联网连接?

修改1

try
{
ComputerInfo ComputerInfoComp = new ComputerInfo();
string Url = "http://illution.dk/"
WebClient Http = new WebClient();
Http.DownloadStringAsync(new Uri(Url));
Http.DownloadStringCompleted += new         DownloadStringCompletedEventHandler(GetModelTypeResponse);
ComputerInfoComp = null;
}
catch (System.Net.WebException e)
{
//
}

3 个答案:

答案 0 :(得分:2)

e.Error处理程序方法中检查GetModelTypeResponse。如果e.Error的类型为WebException,请检查webException.Status值。如果“无法解析主机名”异常

,则值为WebExceptionStatus.NameResolutionFailure
public void GetModelTypeResponse(object sender, DownloadStringCompletedEventArgs e)
{
    var webException = e.Error as WebException;
    if (webException != null && 
        webException.Status == WebExceptionStatus.NameResolutionFailure)
    {
        // log
        return; // ignore
    }

    // proceed
    ..
}

答案 1 :(得分:0)

是的,通过捕获该特定异常。见http://msdn.microsoft.com/en-us/library/ms173160(v=vs.80).aspx

答案 2 :(得分:0)

将您的代码放入try ... catch块。 Google exceptions了解更多信息。