0

我正在使用此代码在 *Form1_Load* 中获取我的应用程序的最新版本:

string result1 = null;
string url1 = "http://site.com/version.html";
WebResponse response1 = null;
StreamReader reader1 = null;

try
{
   HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url1);
   request1.Method = "GET";
   response1 = request1.GetResponse();
   reader1 = new StreamReader(response1.GetResponseStream(), Encoding.UTF8);
   result1 = reader1.ReadToEnd();
 }
 catch (Exception ex)
 {
   // show the error if any.                
 }
 finally
 {
    if (reader1 != null)
         reader1.Close();
    if (response1 != null)
         response1.Close();
 }

问题是,当我关闭服务器时,整个应用程序都卡住了,并且弹出了一个窗口,说:

无法连接到远程服务器

这似乎是合法的。

有没有办法绕过这个崩溃(当服务器关闭时)并打破版本检查?

4

1 回答 1

1

添加一个额外的 catch 块来捕获您看到的特定异常类型......代码看起来像......

try
{
//*yadda yadda yadda*
}
catch (System.Net.WebException WebEx)
{
//*Correctly set up a situation where the rest of your program will know there was a connection problem to the website.*
}
catch (Exception ex)
{
//*Do the error catching you do now*
}
finally
{
//*yadda yadda*
}

这种构造将允许您以与其他类型的异常不同的方式处理 WebException:请注意,所有异常都派生自一个基类 Exception,您可以为这样的用途创建自己的异常。

于 2012-08-15T20:08:42.107 回答