views:

43

answers:

3

I'm using C# WebClient(); to download a file from a server. The problem is when I don't have internet or the server is not responsive, my application crashes trying to download this file. What is the best practice to avoid crashing, to abort and give a notification that connection with a server failed?

+5  A: 

Just handle the exceptions returned by WebClient.DownloadFile:

try
{
    WebClient.DownloadFile(uri, myPath);
}
catch(WebException webEx)
{
     // There was an exception due to network or path problems...
     // Notify the user? 
}
Reed Copsey
Cheers! Thank you for the tip, I used: if (ex.Status == WebExceptionStatus.ProtocolError)
Badr Hari
+1  A: 

A server not being responsive is an exceptional situation that is best dealt with using proper exception handling with a try/catch block.

The exception to handle for WebClient request is a WebException. You can inspect the exception object for further details. The Status property will contain a status value giving you further information what actually went wrong.

Check the samples in MSDN:

try 
{
    WebClient client = new WebClient();

    byte[] pageData = client.DownloadData("http://www.contoso.com");
    string pageHtml = Encoding.ASCII.GetString(pageData);
    Console.WriteLine(pageHtml);

    client.DownloadFile("http://www.contoso.com", "page.htm");
}
catch (WebException webEx) 
{
    Console.WriteLine(webEx.ToString());
    if(webEx.Status == WebExceptionStatus.ConnectFailure) 
    {
        Console.WriteLine("Are you behind a firewall?  If so, go through the proxy server.");
    }
}
0xA3
Very good post, thank you for you're time...
Badr Hari
@Badr Hari: You're welcome. Good luck with your project.
0xA3
+1  A: 

If it's interactive, then yes that would be the best thing to do upon catching the relevant exception. Whether you aborted everything or gave a message (and whether that message was modal or non-modal) would depend on your overall UI. Generally, aborting is more acceptable in the command line or in a web app (with appropriate response for each), aborting just that operation with an error message is more appropriate for a GUI app.

If it was something running as a service etc. you would want to log the exception and go on to the next operation, possibly with some degree of back-off (two exceptions in a row, wait for a bit as the network might be down entirely; another exception, wait longer this time).

In either case you should explicitly catch WebExceptions (and perhaps IOException from the attempt to save the file failing) and let other exceptions (which are more likely to be from bugs in the application) be caught by your overall exception handling strategy.

Jon Hanna