Free Support Forum - aspose.com

Get NullReferenceException while replace keywords

Hi,


I get a strange error while replace keywords in word document.

Please see my code below:

var fileName = “paper template 2.docx”;
var doc = new Document(fileName);

//Replace keywords of investigation.
var regex = new Regex("\[[^\[\]]*\]");
doc.Range.Replace(regex, new ReplaceKeywordEvaluator(), true);
doc.Save(fileName, SaveFormat.Docx);

Note:
1. ReplaceKeywordEvaluator and test documents are in attached .zip file.
2. The keywords in word document as this: [xxx], the keywords should be replaced with real data.

Issues:
1. If I test it with “paper template 2.docx”, then I will get the document, but keywords: [Introduction], [Conclusion] and [Questions] didn’t be replaced in correct location.
2. If I test it with “paper template.docx” then I get NullReferenceException while execute this line: doc.Range.Replace(regex, new ReplaceKeywordEvaluator(), true);.

Could you please help me to correct the 2 problems?

Hi

Thanks for your request. Unfortunately, I cannot reproduce the problem on my side. I use the latest version of Aspose.Words for testing. You can download it from here:

http://www.aspose.com/community/files/51/.net-components/aspose.words-for-.net/category1188.aspx

Also, please try to change your code as shown below:

doc.Range.Replace(regex, new ReplaceKeywordEvaluator(), false);

Best regards,

Thanks for your help!


I changed the code as you mentioned and now it works for me(I use version 9.5). Could you please explain the difference of using true/false in doc.Range.Replace(regex, new ReplaceKeywordEvaluator(), false); since I didn’t understand why the exception thrown.

For the location issue, I’ve solved it according to this thread: http://www.aspose.com/community/forums/88274/inserthtml-within-a-paragraph/showthread.aspx#88274. If someone have similar issue, you may refer to the URL too.

Hi

Thanks for your request. This parameter specifies the direction of replacing process. If it is false Aspose.Words will replace from the end of the document to the beginning. Since you are modifying the document tree upon your replacing process, it is recommended to replace from the end of the document. In this case every next occurrence will be processed in the untouched part of the document tree.

It is perfect that you managed to resolve your second issue. Please feel free to ask in case of any issues, we are always glad to assist you.

Best regards,

Thanks a lot! Now I got it.