I'm trying to duplicate the docx file contents and save them within the same file using OpenXML in C#
Here is the code:
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(wordFileNamePath, true))
{
foreach(OpenXmlElement element in wordDoc.MainDocumentPart.Document.ChildElements)
{
OpenXmlElement cloneElement = (OpenXmlElement)element.Clone();
wordDoc.MainDocumentPart.Document.Append(cloneElement);
}
wordDoc.MainDocumentPart.Document.Save();
}
The code is working fine and does what I need. My problem is that the resulting docx file is partially corrupted. When I open my file I get the following two messages:
Clicking on 'OK' then 'Yes' will open the file normally. However, the file keeps being corrupted until I 'save as' it (with the same or with a different name). That's how the new saved file becomes fixed.
By using the Open XML SDK 2.5 Productivity Tool for Microsoft Office, I can Validate the file and see the reflected code. Validating the file will give the following 5 errors:
So I think that "Clone" function that I use in my code copies the element as it is so when it is appended to the document, some IDs duplications occur.
Any idea to get a proper working DOCX file after duplicating itself? Any alternative code is appreciated.