title: OpenXML Find Replace Text
body: <p><strong>Environment</strong></p>
  
  <p>Visual Studio 2017 C# (Word .docx file)</p>
  
  <p><strong>Problem</strong></p>
  
  <p>The find/replace only replaces "{Today}" - it fails to replace the "{ConsultantName}" field. I've checked the document and tried using different approaches (see commented-out code) but no joy. </p>
  
  <p>The Word document has just a few paragraphs of text - there are no tables or text boxes in the document. What am I doing wrong?</p>
  
  <p><strong>Update</strong></p>
  
  <p>When I inspect <strong>doc_text</strong> string, I can see "{Today}" but "{ConsultantName}" is split into multiple runs. The opening and closing braces are not together with the word - there are XML tags between them:</p>
  
  <pre><code>{&lt;/w:t&gt;&lt;/w:r&gt;&lt;w:proofErr w:type="spellStart"/&gt;&lt;w:r w:rsidR="00544806"&gt;&lt;w:t&gt;ConsultantName&lt;/w:t&gt;&lt;/w:r&gt;&lt;w:proofErr w:type="spellEnd"/&gt;&lt;w:r w:rsidR="00544806"&gt;&lt;w:t&gt;}
  </code></pre>
  
  <p><strong>Code</strong></p>
  
  <pre><code>    string doc_text = string.Empty;
      List&lt;string&gt; s_find = new List&lt;string&gt;();
      List&lt;string&gt; s_replace = new List&lt;string&gt;();
      // Regex regexText = null;
  
      s_find.Add("{Today}");
      s_replace.Add("24 Sep 2018");
      s_find.Add("{ConsultantName}");
      s_replace.Add("John Doe");
  
      using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, true))
      {
          // read document
          using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
          {
              doc_text = sr.ReadToEnd();
          }
  
          // find replace
          for (byte b = 0; b &lt; s_find.Count; b++)
          {
              doc_text = new Regex(s_find[b], RegexOptions.IgnoreCase).Replace(doc_text, s_replace[b]);
              // regexText = new Regex(s_find[b]);
              // doc_text = doc_text.Replace(s_find[b], s_replace[b]);
              // doc_text = regexText.Replace(doc_text, s_replace[b]);
          }
  
          // update document
          using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
          {
              sw.Write(doc_text);
          }
      }
  </code></pre>