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

Victor Rodrigues picture Victor Rodrigues · Mar 19, 2010 · Viewed 40.8k times · Source

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?

Answer

Geoff Tanaka picture Geoff Tanaka · May 17, 2010

I also ran into this problem and actually found the answer here: http://www.aspmessageboard.com/showthread.php?t=230778

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