locked
Add custom xml to word document without closing the document. RRS feed

  • Question

  • I have an .NET application that opens word document within itself. When a certain event is raised we create a content control around the selected word(s) on the word document and then also add some customized string value to custom xml as part of the item1.xml file.

    Since our application already has the word file open and has a write lock on it, we have to save and close word. Then write to item1.xml and then reopen the file in our application.
    But, since we open and close, this can be seen by the client. Is there a neat way of doing this where we do not need to close word document?
    Thursday, July 29, 2010 10:41 AM

All replies

  • Code that I use to create custom xml:
     

    using (Package package = Package.Open(fullDocumentPath, FileMode.Open,
                   FileAccess.ReadWrite))
                    {
                        Uri uriPartTarget = new Uri("/customXml/item1.xml", UriKind.Relative);


                        if (!package.PartExists(uriPartTarget))
                        {
                            PackagePart customXml = package.CreatePart(uriPartTarget,
                                "application/vnd.openxmlformats-officedocument.customXmlProperties+xml");

                            using (Stream partStream = customXml.GetStream(FileMode.OpenOrCreate,
                                FileAccess.ReadWrite))
                            {
                                xmlDoc.Save(partStream);
                            }
                        }
                        else
                        {
                            package.DeletePart(uriPartTarget);
                            PackagePart customXml = package.CreatePart(uriPartTarget,
                                "application/vnd.openxmlformats-officedocument.customXmlProperties+xml");

                            using (Stream partStream = customXml.GetStream(FileMode.OpenOrCreate,
                                FileAccess.ReadWrite))
                            {
                                xmlDoc.Save(partStream);
                            }
                        }

                    }
    Thursday, July 29, 2010 10:53 AM