Davidp04
Davidp04

Reputation: 145

replacing carriage returns with breaks in a string for html asp.net

I have a multiline textbox in an asp.net user control for typing in content to send a mass email from the site login. The HTML includes a placeholder{Message} which is being filled from the text box with

string message = txtbxEmailBody.Text;
message.Replace("\n", "<br />");
message.Replace("\r", "<br />");
message.Replace(Environment.NewLine, "<br />");

string body = string.Empty;
using (StreamReader welcomeEmailReader = new StreamReader(Server.MapPath("htmlpath")))
{
    body = welcomeEmailReader.ReadToEnd();
}
body = body.Replace("{Message}", message);

I put replace in for newline carriage return and Environment.NewLine just to be safe but only carriage return should be necessary. when I traced it I found that the replace did nothing, I assume because carriage return is a special charter in the string and is not read literally by the method? Anyway I just need to know how to replace the carriage returns and new lines with breaks for the HTML

Upvotes: 0

Views: 3072

Answers (1)

Justin Niessner
Justin Niessner

Reputation: 245489

Replace doesn't perform the operation in place. The method instead returns a new instance of the modified string.

Your code doesn't store that returned value anywhere. Try setting the message variable like this:

string message = txtbxEmailBody.Text
                               .Replace(Environment.NewLine, "<br />")
                               .Replace("\n", "<br />")
                               .Replace("\r", "<br />");

Upvotes: 3

Related Questions