C# - 如果无法连接到远程服务器,则抛出异常

时间:2011-06-26 15:38:33

标签: c# .net windows

如果我方法中的函数失败,我试图抛出一个异常,到目前为止我的代码如下:

 if (sourceFile.Exists)
            // Would be nice to add ticker / spinner, while the file header on the remote server is being read!!
            {
                var request = (HttpWebRequest)WebRequest.Create(@"http://google.com/test.zip");
                request.Method = "HEAD";
                var response = (HttpWebResponse)request.GetResponse();

                if (response.LastModified > sourceFile.LastWriteTime)
                {

                    Download_Click(sender, e);

                    // use response.GetStream() to download the file.
                }

2 个答案:

答案 0 :(得分:2)

根据HttpWebRequest文档,如果请求超时或在处理时发生其他错误,则会从GetResponse抛出WebException

您应该能够在代码中捕获它。

答案 1 :(得分:1)