I am trying to remove a document part from a Word document using the Open XML API using roughly their sample code (), and it fails when I try to obtain the flattened XML string.
Here is the code:
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open("C:\\temp\\junk.docx", true))
{
MainDocumentPart? mainPart = wordDoc.MainDocumentPart;
if (mainPart is not null && mainPart.DocumentSettingsPart is not null)
{
mainPart.DeletePart(mainPart.DocumentSettingsPart);
}
return wordDoc.ToFlatOpcString();
}
ToFlatOpcString throws an error:
"Entries cannot be opened multiple times in Update mode"
I am specifically trying to get the resulting document as a flat OPC string.
What am I doing wrong?
UPDATE: We were able to resolve this by constructing the WordprocessingDocument using an explicit memory stream, disposing of the initial WordprocessingDocument (after deleting the Part), then reopening a new WordprocessingDocument using that same memory stream and then calling ToFlatOpcString on the second WordprocessingDocument. Seems like a bug in the OpenXML API, but this worked as a workaround.