I used AltChunk object to copy data from a docx file to a rich text content control in another file. The copy works fine. But now the content control cannot be cast into a SdtElement in OpenXml nor to a ContentControl in VSTO.
This is the code I used
SdtElement sdtElement = destinationdocument.MainDocumentPart.Document.Body.Descendants<SdtElement>().Where(b => b.SdtProperties.GetFirstChild<Tag>() != null).FirstOrDefault();
string altChunkId = "AltChunkId" + Guid.NewGuid().ToString();
AlternativeFormatImportPart chunk = destinationdocument.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImport PartType.WordprocessingML, altChunkId);
chunk.FeedData(File.Open("sourceFile", FileMode.OpenOrCreate));
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
sdtElement.RemoveAllChildren();
sdtElement.Append(altChunk);
the first time the code works fine. But at the second run the first line throws an unable to cast exception. The same problem occurs while using VSTO at the client side the ContentControl object cannot hold the content control in which the AltChunk was inserted. Somehow this procedure corrupts the rich text content control.
Is there anything I am doing wrong? Or is there a better alternative?
wordDocument.MainDocumentPart.Document.Body.Descendants<SdtElement>()returnsIEnumerable<SdtElement>and you are assiging it toSdtElemtnt. Try usingvaror the actual return type.Update:
Your code is a working one. What you are doing wrong is this line
sdtElement.RemoveAllChildren();An sdt element (Content control) contains other elements like sdtPr (content control properties), sdtContent (the actual content inside the content control) etc. as in the below eg.
What your
sdtElement.RemoveAllChildren();doing is to delete everything inside the sdt element and replacing them as:Which is making your program to throw exception on secondrun as in line
destinationdocument.MainDocumentPart.Document.Body.Descendants<SdtElement>().Where(b => b.SdtProperties.GetFirstChild<Tag>() != null).FirstOrDefault();your replaced document sdt element has noSdtPropertiesand also noTagorsdtContent.To workaround this problem try inserting your altchunk block into the content control content element (
sdtContent) instead of the sdt element directly as below:Hope this helps!