aggicd
aggicd

Reputation: 737

C# creating Word file - Error opening file

I am creating some word files (and replacing some words) from word template using this code snippet:

File.Copy(sourceFile, destinationFile, true);

try
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(destinationFile, true))
    {
        string docText = null;
        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        foreach (KeyValuePair<string, string> item in keyValues)
        {
            Regex regexText = new Regex(item.Key);
            docText = regexText.Replace(docText, item.Value);
        }

        using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
        {
            sw.Write(docText);
        }
    }
}

But when I am trying to open the produced file I get this error:

We're sorry. We can't open XXX.docx because we found a problem with its contents

XML parsing error Location:Part:/word/document.xml, Line:2, Column:33686

Here are the contents of document.xml in the specific place:

.....<w:szCs w:val="20"/><w:lang w:val="en-US"/></w:rPr><w:t>&nbsp;</w:t></w:r><w:proofErr w:type="spellEnd"/>....

Where 33686 is the position of the &nbsp. How I can fix that problem?

EDIT In another file that produced correctly in the same position there are some random characters I used for testing which are used also in the title of the document

Upvotes: 0

Views: 337

Answers (1)

Micah
Micah

Reputation: 471

It looks like you're using regular expressions to directly modify XML, which is typically going to lead to difficult-to-troubleshoot issues like this, especially if any of your regexes match anything that could be interpreted as XML.

As an alternative, you may want to investigate that WordProcessDocument class more deeply. It looks like it has strongly-typed objects like Paragraph that you can modify more safely.

Upvotes: 1

Related Questions