I am trying to use C# to replace a specific string of text on an entire DOCX file with a line break (newline).
The string of text that I am searching for could be in a paragraph or in a table in the file.
I am currently using the code below to replace text.
using (WordprocessingDocument doc = WordprocessingDocument.Open("yourdoc.docx", true))
{
var body = doc.MainDocumentPart.Document.Body;
foreach (var text in body.Descendants<Text>())
{
if (text.Text.Contains("##Text1##"))
{
text.Text = text.Text.Replace("##Text1##", Environment.NewLine);
}
}
}
ISSUE: When I run this code, the output DOCX file has the text replaced with a space (i.e. " ") instead of a line break.
How can I change this code to make this work?
run.AppendChild(new Break());
will probably create a new line. But how can I have that put into the document only where it is supposed to replace the text? – Levitus