Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have this following code for bringing page attachments to the user:

private void GetFile(string package, string filename) {     var stream = new MemoryStream();      try     {         using (ZipFile zip = ZipFile.Read(package))         {             zip[filename].Extract(stream);         }     }     catch (System.Exception ex)     {         throw new Exception("Resources_FileNotFound", ex);     }      Response.ClearContent();     Response.ClearHeaders();     Response.ContentType = "application/unknown";      if (filename.EndsWith(".docx"))     {         Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";     }      Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");     Response.BinaryWrite(stream.GetBuffer());     stream.Dispose();     Response.Flush();     HttpContext.Current.ApplicationInstance.CompleteRequest(); } 

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

At first I didn't know if the problem was at uncompressing the zip file that contained the .docx, so instead of putting the output file only in the response, I saved it first, and the file opened successfully, so I know the problem should be at response writing.

Do you know what can be happening?

like image 543
Victor Rodrigues Avatar asked Mar 19 '10 13:03

Victor Rodrigues


People also ask

How do I uncorrupt a DOCX file?

Solution 1: Use the inbuilt Microsoft Word Repair tool Open Microsoft Word and click on File. Click Open and select the . docx file with the problem. Click the down arrow next to the Open button and choose Open and repair.

How do I view a docx file in asp net?

The uploaded Word Document file is first saved into a Folder named Temp within the Project Folder and then the Word Document file is converted into HTML string using Microsoft Office Interop Library. Finally the HTML string will be assigned to the InnerHtml property of the HTML DIV.

How do I fix docx in Word?

In Word, select File on the Ribbon, and then select Open. In the Open dialog box, click once to highlight your Word document. Select the arrow on the Open button, and then select Open and Repair.

Is DOCX format safe?

Docx is a zip file of XML, and that can be unsafe. In short, it sucks. almost everything out there is dangerous. Keep yourself patched (many exploits are from bugs) get antivirus, don't use IE, use Chrome or Mozilla.


1 Answers

I also ran into this problem and actually found the answer here:

It turns out that the docx format needs to have Response.End() right after the Response.BinaryWrite.

like image 174
Geoff Tanaka Avatar answered Oct 16 '22 20:10

Geoff Tanaka