Unable to saveAs .docx file after modifications

1

I'm building a software to modify docx files using Microsoft.Interop.Word. Users can add text, tables and so on.

When trying to SaveAs the document, I get a COM or a Cast error depending on the code I'm trying to use.

If I try to close the document before saving, I get the following error :

System.InvalidCastException : 'Unable to cast COM object of type 'Microsoft.Office.Interop.Word.DocumentClass' to interface type 'Microsoft.Office.Interop.Word._Document'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{0002096B-0000-0000-C000-000000000046}' failed due to the following error: The requested object does not exist. (Exception from HRESULT: 0x80010114).'

If I avoid closing the document, I get the following error:

System.Runtime.InteropServices.COMException : 'Word cannot save this file because it is already open elsewhere.

This is my simple Save function :

private Microsoft.Office.Interop.Word.Application _appClass = null;
private Document _doc = null;
private object READONLY = (object)false;
public object M = System.Reflection.Missing.Value;

public DocBrowser()
{
    _appClass = new Microsoft.Office.Interop.Word.Application();
    _doc = _appClass.Documents.Open(ref oldFileName, ref M, ref READONLY,
                                  ref M, ref M, ref M, ref M, ref M, ref M, ref M,
                                  ref M, ref M, ref M, ref M, ref M, ref M);
    InsertText("test text");
    SaveDocx("temp.docx");
}

public void InsertText(string text)
{
    Paragraph oPara;
    object oStyleName = "Normal";
    oPara = _doc.Content.Paragraphs.Add(ref M);
    oPara.Range.Text = text;
    oPara.Range.set_Style(ref oStyleName);
    oPara.Range.InsertParagraphAfter();

    oPara = null;
    oStyleName = null;
}

public void SaveDocx(string newDocPath)
{
    object newFileName = (object)newDocPath;
    object fileType = (object)WdSaveFormat.wdFormatDocumentDefault;

    // Trying to close document first 

    /*if (_doc != null)
    {
        _doc.Close(WdSaveOptions.wdDoNotSaveChanges);
    }*/

    _doc.SaveAs(ref newFileName, ref fileType,
        ref M, ref M, ref M, ref M, ref M, ref M, ref M,
        ref M, ref M, ref M, ref M, ref M, ref M, ref M);
}

I really can't manage to save the file, I also tried to saveAs a PDF file without success.

c#
winforms
ms-word
com
interop
asked on Stack Overflow Sep 30, 2019 by TmZn • edited Sep 30, 2019 by TmZn

1 Answer

0

Turns out you can't SaveAs on an existing file, just deleting the file if it exists and then SaveAs made everything work, still a strange behavior.

answered on Stack Overflow Sep 30, 2019 by TmZn

User contributions licensed under CC BY-SA 3.0