3

The problem is that all supported files works properly (jpg, gif, png, pdf, doc, etc), but .docx files, when i download, it says corrupted and they need to be fixed by Office in order to be opened.

This is my code:

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
Response.BinaryWrite(RptBytes);
stream.Dispose();
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();

I have got solution from some other site,

i.e

It turns out that the docx format needs to have Response.End() right after the Response.BinaryWrite instead of HttpContext.Current.ApplicationInstance.CompleteRequest()

Why are .docx files being corrupted when downloading from an ASP.NET page?

It's working fine but Response.End throws the exception as Thread was being aborted.

Community
  • 1
  • 1
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
  • 1
    My guess is all of your downloads are corrupted, except some file formats are more forgiving than others. An errant byte on a jpg or gif is probably not going to be noticed by the software displaying the image. However, docx files are actually zip files, which are more strict about corrupted bytes. What I would do is: 1. read your file stream into a byte array, 2. close/dispose your stream, then write the byte array to the response via BinaryWrite – Walter Stabosz Dec 02 '13 at 06:12
  • @Walter Stabosz I suppose this could be written as an answer and not as a comment... – Pantelis Natsiavas Dec 02 '13 at 07:00

1 Answers1

3

Copying my comment to an answer:

My guess is all of your downloads are corrupted, except some file formats are more forgiving than others. An errant byte on a jpg or gif is probably not going to be noticed by the software displaying the image. However, docx files are actually zip files, which are more strict about corrupted bytes.

What I would do is:

  1. read your file stream into a byte array
  2. close/dispose your stream
  3. then write the byte array to the Response via BinaryWrite

    // read the file to a byte array byte[] RptBytes = File.ReadAllBytes(pathToFile);

Then follow the code in https://stackoverflow.com/a/15869303/740639

I think your problem is how you are dealing with Response. You could probably just follow the code in that answer and skip the whole byte array part.

Community
  • 1
  • 1
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
  • I referred your link.What is masterPresentation in that.and how can i use that? – Vignesh Kumar A Dec 03 '13 at 06:13
  • `masterPresentation` is a local variable that the user has defined outside of their code sample. I've helped you all that I can at this point. It's beginning to sound to me like you may be in over your head with the programming task with with you have been assigned. – Walter Stabosz Dec 03 '13 at 16:45