Save DOCX - Load DOCX

I have the following code that is saving the byte array of an uploaded DOCX file (attached) to the database and then pulling the information from the database and saving it to the response stream.

protected void linkButtonUpdateEventTemplate_Click(object sender, EventArgs e)
{
    if (!fileUploadEventTemplateUpdate.HasFile)
    {
        SetError("You must select a new file to upload");
        return;
    }
    Var_EventTemplate eventTemplate = VarManager.GetEventTemplate(_eventTemplateID);
    eventTemplate.FileContents = fileUploadEventTemplateUpdate.FileBytes;
    SessionManager.DataBaseConnection.SaveChanges();
    SetSuccess("Template updated");
}

protected void linkButtonDownloadEventTemplate_Click(object sender, EventArgs e)
{
    Var_EventTemplate eventTemplate = VarManager.GetEventTemplate(_eventTemplateID);
    using(MemoryStream ms = new MemoryStream(eventTemplate.FileContents))
    {
        Document doc = new Document(ms, new LoadOptions()
        {
            LoadFormat = LoadFormat.Docx
        });
        doc.Save(Response,
             String.Format("{0}.docx", eventTemplate.Name),
             ContentDisposition.Attachment,
             new DocSaveOptions(SaveFormat.Docx));
    }
}

When I call “doc.Save” with the information above, I receive the following error:

System.ArgumentException: An invalid SaveFormat for this options type was chosen.

Why? and how do I correct the issue?

Hi Miles,

Thanks for your inquiry. You are getting this error because you are passing SaveFormat.Docx to DocSaveOptions Constructor.

DocSaveOptions Constructor initializes a new instance of this class that can be used to save a document in the Doc or Dot format.

OoxmlSaveOptions Constructor initializes a new instance of this class that can be used to save a document in the Docx, Docm, Dotx, Dotm or FlatOpc format.

In your case, please use the OoxmlSaveOptions instead of DocSaveOptions. Please let us know if you have any more queries.

This solved part of the problem but now when I try to open the DOCX file from my computer, I get a warning from Word that the file is corrupted.

Attached is a compressed video of what I’m seeing

Hi Miles,

Thanks for your inquiry. To resolve the problem with DOCX you should simply add Response.End() after sending document to client browser. This will resolve the problem. 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 open your DOCX document in any binary editor. That is why MS Word cannot open this document. If you add Response.End(), content of web page will not be added and document will be valid.

Document doc = new Document(MyDir + "Document.doc");
doc.Save(Response, "Report Out.doc", ContentDisposition.Inline, null);
Response.End();

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.