ThreadAbortException (WebClient using DownloadFile to grab file from server)

Posted by baron on Stack Overflow See other posts from Stack Overflow or by baron
Published on 2010-03-30T03:18:08Z Indexed on 2010/03/30 3:23 UTC
Read the original article Hit count: 528

Hi Everyone,

Referencing my Earlier Question, regarding downloading a file from a server and handling exceptions properly. I am positive that I had this solved, then in classic programming fashion, returned days later to frustratingly find it broken :-(


Updated code:

private static void GoGetIt(HttpContext context)
    {
        var directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe = new FileInfo(......);
                var name = SomeBasicLogicToDecideName();

            //if (!directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe.RefreshExists())
            //{
            //  throw new Exception(string.Format("Could not find {0}.", name));
            //}

            var tempDirectory = ""; //Omitted - creates temporary directory

            try
            {
                directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe.CopyAll(tempDirectory);
                var response = context.Response;
                response.ContentType = "binary/octet-stream";
                response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.zip", name));
                ZipHelper.ZipDirectoryToStream(tempDirectory, response.OutputStream);
                response.End();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                context.Response.StatusCode = 404;
            }
            finally
            {
                tempDirectory.DeleteWithPrejudice();
            }
        }

This was working fine, and returning the zip, otherwise if the file didn't exist returning 404. Then on the client side I could handle this:

public bool Download()
{   
 try
                {
                    using (var client = new WebClient())
                    {
                        client.DownloadFile(name, tempFilePath);
                    }

                }
                catch (Exception)
                {
                    fileExists = false;
                }
return fileExists;
    }

But the problem now is two things.

1) I get System.Threading.ThreadAbortException: Thread was being aborted in the server side try-catch block. Usually this was just a file not found exception. I have no idea what or why that new exception is throwing?

2) Now that a different exception is throwing on the server side instead of the file not found, it would seem I can't use this set up for the application, because back on client side, any exception is assumed to be filenotfound.

Any help, especially info on why this ThreadAbortException is throwing!?!? greatly appreciated. Cheers

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf