1

In my page i am trying to download file. THe file is downloaded successfully but i get System.Threading.ThreadAbortException. So i handled that in my try Catch Block and set the error lable to blank but it doesnt get updated in page.

        catch (System.Threading.ThreadAbortException)
        {
            lblErrorMsg.Text = "dfdf";
        }
        catch (Exception ex)
        {
            lblErrorMsg.Text = "Error while processing you request :<br> Erorr Description : " + ex.Message;
        }

This is my Write file function

  public static void WriteFile(string nameOfFile, string fileContent, HttpResponse writer)
    {
        writer.ClearHeaders();
        writer.ClearContent();

        writer.ContentType = "text/xml";
        writer.AppendHeader("Content-Disposition", "attachment; filename=" + nameOfFile);
        writer.Write(fileContent);
        writer.Flush();
        writer.End();
    }

Can someone tell why label is not set to blank even though it comes under the Catch Block of system.thread.threadabortexceptiopn when i debug code ?

James
  • 1,827
  • 5
  • 39
  • 69

1 Answers1

0

ThreadAbortException happens because you close the Response prematurely, by calling End() method of Response object. This also explains why it's too late to write on the page content. It's not a very annoying error but it would be better to handle it cleanly.

Just check these answers Why Response.Redirect causes System.Threading.ThreadAbortException? or How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download and other answers related to Response and ThreadAbortException to understand it and handle properly by writing a better code for file download, according your usage.

Also please note that doesn't make a great sense to have both a completely rewritten Response stream for a page and some content on it, like a Label.

Community
  • 1
  • 1
AFract
  • 8,868
  • 6
  • 48
  • 70
  • i am not writing any content on label. Just writing exception on label. Links in Your answer not helping me :( can you give me specific solution – James Jan 21 '16 at 09:25
  • Also as you can see in my code that i am not doing response.redirect – James Jan 21 '16 at 09:33
  • First question : you are explicitly emptying the Response content to replace it by your download, and despite this there is a control on your form and you try to write something on it. That's not logic. Second question : have you read the answer of user3412640 on my second link ? I told you the problem is the call to End() method of your Response. – AFract Jan 21 '16 at 09:39
  • The first link about Redirect was for the explanation of what happens, not for a direct fix. – AFract Jan 21 '16 at 09:40