James Buttler
James Buttler

Reputation: 61

C# - Throw an exception if can't connect to remote 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.
                }

Upvotes: 1

Views: 9003

Answers (2)

Mat
Mat

Reputation: 206841

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.

Upvotes: 3

Kinexus
Kinexus

Reputation: 12904

try/catch HttpException

http://msdn.microsoft.com/en-us/library/system.web.httpexception.aspx

Upvotes: 1

Related Questions