Open-XML-SDK
Open-XML-SDK copied to clipboard
Bug with Open XML SDK
I try to create a Word document with AutoSave = false, but resulting document can't be read. If I set AutoSave = true it is Ok.
In english "Word find content that can't be read in document ..."
WordprocessingDocument WordDocX = WordprocessingDocument.Create(outFile, WordprocessingDocumentType.Document, false); MainDocumentPart mainPart = WordDocX.AddMainDocumentPart(); mainPart.Document = new Document(); Body body = mainPart.Document.AppendChild(new Body()); Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); run.AppendChild(new Text("Create test text in body")); WordDocX.Dispose();
Build and run, then try open word document
- OS: Windows 11
- Office version Microsoft® Word 2021 MSO (Version 2308 Build 16.0.16731.20182) 64-bitars
- .NET Target: .NET 6.0
- Windows Forms project
- Visual Studio 2022 ver 17.7.3
- DocumentFormat.OpenXml Version: 2.20.0
I found the problem, If AutoSave is set to false then Dispose is not saving as documentation is saying it should do. Must add a Save before Dispose. Should be a note of that in documentation.
Hi @Lars-O-B, Above your said, "If AutoSave is set to false then Dispose is not saving as documentation is saying it should do." But, when looking through the documentation, here it says autoSave is whether to auto save the created document, link here. So, according to this, the behavior is by design.
If you found something different in the documentation, could you point us to where it is in the documentation. Thanks!
Hi @mikeebowen In the documentation of Dispose it says: "Flushes and saves the content, closes the document, and releases all resources." But that it is false if document is opened with Autosave = false. Then it is not saved, it needs then a Save command before Dispose.
Perhaps not a big deal but it took me some time to realize that.
https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.packaging.openxmlpackage.dispose?view=openxml-2.8.1&devlangs=csharp&f1url=%3FappId%3DDev16IDEF1%26l%3DEN-US%26k%3Dk(DocumentFormat.OpenXml.Packaging.OpenXmlPackage.Dispose)%3Bk(DevLang-csharp)%26rd%3Dtrue
Hi @Lars-O-B, you're right it's not clear in the page you sent, but in the definition of AutoSave, it states that AutoSave "Gets a flag that indicates whether the parts should be saved when disposed." link here.
Are you setting autoSave to false to prevent intermediate/periodic document saves while you are processing the document? If so, the autoSave name may be leading you in the wrong direction here. A better name would be something like saveOnDispose.