0

I have word document which is opening perfectly at server but when i download it using button click event of my website it gets currept. i am using below code on button click to make document download. please help to resolve this problem: i am using .net framework 3.5

 Response.Clear();
 Response.AddHeader("Content-Disposition", "attachment; filename=StandardLetter" + _responseId.ToString() + ".doc");
 Response.ContentType = "application/octet-stream";

 Response.TransmitFile (Server.MapPath("~/document/letter/StandardLetter" + _responseId.ToString() + ".doc"));
Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178

3 Answers3

2

Do you have a Response.End() after that code you posted? If not, you will get extra "html" code from the aspx file added to the transmitted file - thus corrupting it.

EDIT
As Akshay Anand mentioned, a better way would be to call HttpContext.Current.ApplicationInstance.CompleteRequest(); instead of Response.End() see docs. See also this question.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
  • Kesting: Does Response.Flush() works in place of Response.End()? As Response.End() throws abort exception – Akshay Anand May 21 '19 at 21:18
  • Flush() just sends everything that was cached and continues processing. You need that End() to *stop* that processing. You can ignore that exception - that is the way the processing is aborted – Hans Kesting May 22 '19 at 05:16
  • 1
    One issue is whenever such exceptions happen on our web application after a while application becomes very slow and starts spooling. We decided not to use Response.End() due to thread abort, instead used HttpContext.Current.ApplicationInstance.CompleteRequest(); – Akshay Anand May 24 '19 at 04:43
1

Instead try:

Response.ContentType ="application/msword";

I dont use Word but for Excel I use:

Response.ContentType = "application/x-msexcel"
Markive
  • 2,350
  • 2
  • 23
  • 26
1

Ok well here is the code I use, it's vb but easily converted ;)

 Response.ContentType = "application/pdf"
        Dim byteArray As Byte() = File.ReadAllBytes(MergedFile)

        Response.AddHeader("Content-Disposition", "attachment;filename=""" & ShortFilename & """")
        Response.AddHeader("Content-Length", byteArray.Length)
        Response.BinaryWrite(byteArray)
        Response.Flush()
        Response.End()

This works for PDF and by changing .ContentType to Excel spits that out too.. So I assume this will take any MIME type. Good luck!

I take my pdf document called MergedFile and convert it to a byte(), I give it a 'ShortName' that can be entered by the user. Content-Length is very important..

Markive
  • 2,350
  • 2
  • 23
  • 26