0

Using C# in VS, I am trying to change the author name in track changes found in a word document header based on their dates. Using the debugger, it seems that the author's name is getting changed, but the document changes are not getting saved. I have included the 'headerPart.Header.Save()' line, which would presumably do trick, but no luck. I need help saving the document after the changes have been made - thanks!

private void changeRevAuthor(string docPath, string input_project_date)
    {
        using (Stream stream = System.IO.File.Open(docPath, FileMode.OpenOrCreate))
        {
            stream.Seek(0, SeekOrigin.End);  
            XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
            using (WordprocessingDocument document = WordprocessingDocument.Open(stream, true))
            {
                foreach (HeaderPart headerPart in document.MainDocumentPart.HeaderParts)
                {
                    foreach (OpenXmlElement headerElement in headerPart.RootElement.Descendants())
                    {
                        OpenXmlElement children = headerPart.RootElement;
                        XElement xchildren = XElement.Parse(children.OuterXml);
                        var ychildren = xchildren.Descendants().Where(x => x.Attributes(w + "author").Count() > 0);

                        foreach (XElement descendant in ychildren)
                        {
                            var date = descendant.Attribute(w + "date").ToString().Substring(8, 10);
                            if (DateTime.Parse(date) > DateTime.Parse(input_project_date))
                            {
                                descendant.SetAttributeValue(w + "author", "new author name");
                                Debug.WriteLine("this is the new one" + descendant);
                            }
                        }
                    }
                    headerPart.Header.Save();
                    Debug.WriteLine("We got here");
                }
                document.Close();

            }
        }
    }

1 Answers1

0

Use MainDocumentPart save() method to save the changes in the document.

ie:document.MainDocumentPart.Document.Save();

Kunalan Krish
  • 232
  • 1
  • 14
  • Thank you for the reply - the code currently has a block for the main document, which runs fine, and another for the header component. After adding the line above, I keep running into a 'Entries cannot be opened multiple times in Update mode.' error. Any suggestions? – thesyllabus Jul 08 '16 at 14:09
  • Also, after using the save line on solely the header code (removing any maindocument code), it still does not save. – thesyllabus Jul 08 '16 at 15:04