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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With