none
Adding Text To an Existing Word Document (.docx) results in file corruption RRS feed

  • Question

  • Hi, Im trying to add text to a document copied from one directory to another. Heres my code:

                string dir = Directory.GetCurrentDirectory();
                string filename = dir + "\\templates\\TWord.docx";
                string fn = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments)+ "Doc1.docx";
                File.Copy(filename, fn, true);
                String txt = "Testing";
                WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(fn, true);
                DocumentFormat.OpenXml.Wordprocessing.Document document = wordprocessingDocument.MainDocumentPart.Document;
                DocumentFormat.OpenXml.Wordprocessing.Body body = document.MainDocumentPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                DocumentFormat.OpenXml.Wordprocessing.Paragraph para = body.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());

                Run run = para.AppendChild(new Run());
                run.AppendChild(new Text(txt));

                wordprocessingDocument.Close();

    The file copies fine, and begins the process however when I try to open the file after the run.AppendChild() is executed word gives the error: We're Sorry We Cant Open Doc1 Because we found a problem with its contents"

    Details: 

    Unspecified error

    Location: Part:/word/document.xml,Line:1,column:0

    Thursday, August 2, 2018 7:10 PM

All replies

  • Your problem is this line of code:

    DocumentFormat.OpenXml.Wordprocessing.Body body = 
       document.MainDocumentPart.Document.AppendChild(
       new DocumentFormat.OpenXml.Wordprocessing.Body());

    If you start with an existing document, that document will already contain a <w:body> element. A Word document can have only one <w:body>. You need to use something like the following to get the Body:

    DocumentFormat.OpenXml.Wordprocessing.Document document = 
      wordprocessingDocument.MainDocumentPart.Document;
    Body body = document.Body;


    Cindy Meister, Office Developer/Word MVP, <a href="http://blogs.msmvps.com/wordmeister"> my blog</a>

    Sunday, August 5, 2018 9:46 AM
    Moderator