Save a Document to HttpResponse

Hi,
I am trying to save a document to a stream so that it can be used by a HttpResponse object. it all works except the file is corrupted when I try to open it. Please review the code snippet below and advise me what change(s) I need to make.

using (MemoryStream stream = new MemoryStream())
{
_document.Save(stream, SaveFormat.Docx);
stream.Position = 0;

            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.AddHeader("Content-Description", "File Transfer");
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("content-disposition", "attachment; filename=\"" + _documentNameDated + ".docx\"");
            Response.AddHeader("Content-Transfer-Encoding", "binary");
            Response.Cache.SetExpires(DateTime.Now.AddMinutes(1));
            Response.AddHeader("Cache-Control", "must-revalidate");
            Response.AddHeader("Pragma", "public");

            stream.WriteTo(Response.OutputStream);
        }
        Response.Flush();        
        HttpContext.Current.ApplicationInstance.CompleteRequest();

Thanks

@Cenozon,

This does not seem to be an issue in Aspose.Words. You can resolve the problem with DOCX by simply adding Response.End() after sending document to client browser. For some reasons, when you save a DOCX document to client browser, content of web page is added at the end of the document, you can see this if you open your DOCX document in any binary editor. That is why Microsoft Word cannot open this document. If you add Response.End(), content of web page will not be added and document will be valid. Hope, this helps.

Yes, that was all that was needed was to close the response and now it works.

Thanks for the help

@Cenozon,

Thanks for your feedback. Please let us know anytime you have any further queries.