Search code examples
c#asp.net-mvcopenxmlstreamreader

streamReader.ReadToEnd() return just header OpenXML


Please, I want to find a word and replace it with another word in word doccument using openXML

  I use this method

public static void AddTextToWord(string filepath, string txtToFind,string ReplaceTxt)
    {

     WordprocessingDocument wordDoc = WordprocessingDocument.Open(filepath, true);
        string docText = null;
        StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream());
        docText = sr.ReadToEnd();
        System.Diagnostics.Debug.WriteLine(docText);
        Regex regexText = new Regex(txt);
        docText = regexText.Replace(docText,txt2);
        StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create));
        System.Diagnostics.Debug.WriteLine(docText);         
        wordDoc.Close();
    }

but

docText

return just the head of the page that the xml shema of the document.

  <?xml version="1.0" encoding=.......

Solution

  • Check Your Strings

    If you want to replace a specific word or phrase within your existing content, you may just want to use the String.Replace() method as opposed to performing a Regex.Replace() which may not work as expected (as it expects a regular expression as opposed to a traditional string). This may not matter if you expect to use regular expressions, but it's worth noting.

    Ensure You Are Pulling The Content

    Word Documents are obviously not as easy to parse as plain text, so in order to get the actual "content", you may have to use an approach similar to the one mentioned here that targets the Document.Body properties instead of reading using a StreamReader object :

    docText = wordDoc.MainDocumentPart.Document.Body.InnerText;
    

    Performing Your Replacement

    With that said, you currently appear to be reading the contents of your file and storing it in a string called docText. Since you have that string and know your values to find and replace, just call the Replace() method as seen below :

    docText = docText.Replace(txtToFind,ReplaceTxt);
    

    Writing Out Your Content

    After performing the replacement, you'll just need to write your updated text out to a stream :

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