简体   繁体   中英

C# - Throw an exception if can't connect to remove server

I am trying to get an exception thrown if the function in my method fails, my code is as follows so far:

 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.
                }

According to the HttpWebRequest docs, a WebException is thrown from GetResponse if the request times out or another error occurs while processing it.

You should be able to catch that in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM