From 5e6e6c63cd3985bba8e2fe58aabf01b20f80ed89 Mon Sep 17 00:00:00 2001 From: adricl Date: Wed, 5 Feb 2020 09:51:16 +1100 Subject: [PATCH] Fix to crash when text replacer crash when replacement string is empty. --- OpenXmlPowerTools/TextReplacer.cs | 2 +- OpenXmlPowerToolsExamples/TextReplacer02/TextReplacer02.cs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/OpenXmlPowerTools/TextReplacer.cs b/OpenXmlPowerTools/TextReplacer.cs index e28b1d70..dca45909 100644 --- a/OpenXmlPowerTools/TextReplacer.cs +++ b/OpenXmlPowerTools/TextReplacer.cs @@ -149,7 +149,7 @@ private static object WmlSearchAndReplaceTransform(XNode node, return (object)g; string textValue = g.Select(r => r.Element(W.t).Value).StringConcatenate(); XAttribute xs = null; - if (textValue[0] == ' ' || textValue[textValue.Length - 1] == ' ') + if (textValue.Length > 0 && (textValue[0] == ' ' || textValue[textValue.Length - 1] == ' ')) xs = new XAttribute(XNamespace.Xml + "space", "preserve"); return new XElement(W.r, g.First().Elements(W.rPr), diff --git a/OpenXmlPowerToolsExamples/TextReplacer02/TextReplacer02.cs b/OpenXmlPowerToolsExamples/TextReplacer02/TextReplacer02.cs index 7071816b..461f6460 100644 --- a/OpenXmlPowerToolsExamples/TextReplacer02/TextReplacer02.cs +++ b/OpenXmlPowerToolsExamples/TextReplacer02/TextReplacer02.cs @@ -20,7 +20,7 @@ static void Main(string[] args) var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second)); tempDi.Create(); - DirectoryInfo di2 = new DirectoryInfo("../../"); + DirectoryInfo di2 = new DirectoryInfo("../../../"); foreach (var file in di2.GetFiles("*.docx")) file.CopyTo(Path.Combine(tempDi.FullName, file.Name)); @@ -50,6 +50,8 @@ static void Main(string[] args) TextReplacer.SearchAndReplace(doc, "the", "this", true); using (WordprocessingDocument doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test09.docx"), true)) TextReplacer.SearchAndReplace(doc, "===== Replace this text =====", "***zzz***", true); + using (WordprocessingDocument doc = WordprocessingDocument.Open(Path.Combine(tempDi.FullName, "Test09.docx"), true)) + TextReplacer.SearchAndReplace(doc, "***zzz***", "", true); } } }