I have tried to recreate this bug by creating a document as you explained above, but I cannot get it to crash. Can you please send me the following by email.
1) The document that is causing the crash,
2) The code you are running that is causing the crash.
By the way, the code you have written above is great. However it will not be efficient if a Paragraph contains the same match more than once. For example if a Paragraph contained the following "<c>Hello</c> <c>Hello</c> <c>Hello</c>"
your example would replace all instances of <c>Hello</c> with Hello in the first call to ReplaceText() the following 2 calls are wasted CPU time.
The below code is more efficient as it exploits the fact that we know the start index and length of every match, therefore we do not need to search the entire Paragraph using ReplaceText().
// Load a document.
using (DocX document = DocX.Load(@"Test.docx"))
// Create a regex to replace text.
Regex regex = new Regex("<c>(.*?)</c>", RegexOptions.Singleline);
// Loop through each Paragraph in this document.
foreach (Paragraph p in document.Paragraphs)
// Get a collection of matches.
MatchCollection matches = regex.Matches(p.Text);
* We must process matches in reverse order so that all matches before this match
* are not shifted by the change in text length caused by Replace.
foreach (Match match in matches.Cast<Match>().Reverse())
// Remove the matched text
p.RemoveText(match.Index, match.Length, false);
// Insert the matched text after it has been regexed.
p.InsertText(match.Index, regex.Replace(match.Value, "$1"), false);
* Save all changes made to this document as Test2.docx.
* I always do this the first time I run a new DocX program incase I break the origional file.
}// Release the document from memory.
I hope you find this useful,