Replace text in RTF string - Results aren't kept
Asked Answered
rtf
P

0

6

Sorry for the lame title, but couldn't think of a better way to say it, and have Bingleing for a few days on this.

I have code that reads in an RTF file, which I have put placeholders in to act as merge fields. The code will replace the text, but when the file is saved back, the new values aren't showing up.

var fileName = @"C:\Users\James\SkyDrive\Sandbox\MailMerge\MailMerge\templates\Template1.rtf";
StreamReader sr = new StreamReader(fileName);
string text = sr.ReadToEnd();
sr.Close();
text = text.Replace("{\\{Title\\}\\}", "Mr.");
text = text.Replace("{\\{LastName\\}\\}", "Johnson");
text = text.Replace("{\\{FirstName\\}\\}", "James");

RTF before replacing: {\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} {*\generator Riched20 6.2.9200}\viewkind4\uc1 \pard\sa200\sl276\slmult1\f0\fs22\lang9 Hi {{Title}} {{LastName}}\par How are you doing, {{FirstName}}\par }

RTF after replacing: {\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} {*\generator Riched20 6.2.9200}\viewkind4\uc1 \pard\sa200\sl276\slmult1\f0\fs22\lang9 Hi \Mr. \Johnson\par How are you doing, \James\par }

RTF after being saved and opened in notepad: {\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}} \viewkind4\uc1\pard\sa200\sl276\slmult1\lang9\f0\fs22 Hi . \par How are you doing, \par }

Is there some other step I need to do, which will save the file in the correct format? I have tried using the RichTextBox control as well, loading the string into it, then calling the Save() method. this gives me the same results.

Thanks, James

Figured it out after reading this post, Cleaning up RTF text and using the following code:

var fileName = @"C:\Users\James\SkyDrive\Sandbox\MailMerge\MailMerge\templates\Template1.rtf";
StreamReader sr = new StreamReader(fileName);
string text = sr.ReadToEnd();
sr.Close();
rtb.Rtf = text;
rtb.Text = rtb.Text.Replace("{{Title}}", "Mr.");
rtb.Text = rtb.Text.Replace("{{LastName}}", "Johnson");
rtb.Text = rtb.Text.Replace("{{FirstName}}", "James");
rtb.SaveFile(@"C:\Users\James\SkyDrive\Sandbox\MailMerge\MailMerge\templates\Johnson2.rtf");
Postaxial answered 6/9, 2012 at 20:22 Comment(1)
Ok, after reading this post, https://mcmap.net/q/936047/-cleaning-up-rtf-text, I figured it out.Postaxial

© 2022 - 2024 — McMap. All rights reserved.