Webclient using download file to grab file from server - handling exceptions

Posted by baron on Stack Overflow See other posts from Stack Overflow or by baron
Published on 2010-03-15T03:14:15Z Indexed on 2010/03/15 3:19 UTC
Read the original article Hit count: 707

Hello everyone,

I have a web service in which I am manipulating POST and GET methods to facilitate upload / download functionality for some files in a client/server style architecture. Basically the user is able to click a button to download a specific file, make some changes in the app, then click upload button to send it back.

Problem I am having is with the download. Say the user expects 3 files 1.txt, 2.txt and 3.txt. Except 2.txt does not exist on the server.

So I have code like (on server side):

public class HttpHandler : IHttpHandler
{

    public void ProcessRequest
    {
       if (context.Request.HttpMethod == "GET")
       {
          GoGetIt(context)
       }
    }

private static void GoGetIt(HttpContext context)
{
     var fileInfoOfWhereTheFileShouldBe = new FileInfo(......);

     if (!fileInfoOfWhereTheFileShouldBe.RefreshExists())
     {
          throw new Exception("Oh dear the file doesn't exist");
     }

    ...

So the problem I have is that when I run the application, and I use a WebClient on client side to use DownloadFile method which then uses the code I have above, I get:

WebException was unhandled: The remote server returned an error: (500) Internal Server Error.

(While debugging) If I attach to the browser and use http://localhost:xxx/1.txt I can step through server side code and throw the exception as intended. So I guess I'm wondering how I can handle the internal server error on the client side properly so I can return something meaningful like "File doesn't exist". One thought was to use a try catch around the WebClient.DownloadFile(address, filename) method but i'm not sure thats the only error that will occur i.e. the file doesn't exist.

© Stack Overflow or respective owner

Related posts about c#

Related posts about webclient