mribot
mribot

Reputation: 529

Word Doc. getting corrupted by open XML find & replace

I am using following function in C# to find & replace in word doc using open xml sdk.

// To search and replace content in a document part.
public static void SearchAndReplace(string document)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        string docText = null;
        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        Regex regexText = new Regex("Findme");
        docText = regexText.Replace(docText, "Before *&* After"); // <-- Replacement text

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

Code works fine for most of the cases but the case above where replace text has "&" there is an error while opening the document..

error says : The fileXYZ cannot be opened because there are problem with contents. details : Illegal name character.

This error also persisted when i used "<w:br/>" in replace string to insert new line at the end of the string. But i removed the error by adding a space after "<w:br/> ".

PS: "replace text" is in indicated with a comment.

Upvotes: 0

Views: 1633

Answers (1)

Hari Raj
Hari Raj

Reputation: 11

// To search and replace content in a document part.

public static void SearchAndReplace(string document)
{
    using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
    {
        string docText = null;
        using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
        {
            docText = sr.ReadToEnd();
        }

        Regex regexText = new Regex("Findme");
        docText = regexText.Replace(docText, new System.Xml.Linq.XText("Before *&* After").ToString()); // when we replace string with "&" we need to convert like this

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

Upvotes: 1

Related Questions