I like to create a text reader and a text writer for this task as you don't have to worry about what
the line terminator is. Just keep calling read line and write line.
Here's a method I wrote to handle this:
public static string ToHtmlNewLine(string text) {
if (text == null) return null;
int length;
StringReader reader;
StringWriter writer;
StringBuilder builder;
string line;
length = text.Length() * 1.2; //apply some padding to avoid array resizing, you probably want to
//tweak this value for the size of the strings you're using
reader = new StringReader(text);
builder = new StringBuilder(length);
writer = new StringWriter(builder) ;
line = reader.ReadLine();
if (line != null) {
/*this if then while loop avoids adding an extra blank line at the end of the conversion
* as opposed to just using:
* while (line != null) {
* writer.Write(line);
* writer.WriteLine("<br/>");
*/
writer.Write(line);
line = reader.ReadLine();
while (line != null) {
writer.WriteLine("<br/>");
writer.Write(line);
line = reader.ReadLine();
}
}
return writer.ToString();
}
CK wrote:
Hi all,
I have a textarea control. I am putting it's value in an html email. The
problem is that the new lines are being ignored. I want to take the
controls value and replace any newline carriage returns, with an html <br>
tag. I tried the following function but it doesn't work. Does anyone have
any ideas how to accomplish this? Thanks in advance. ~ CK
string getComments()
{
string s = tbxComments.Text;
Regex r = new Regex("/\n/g");
s = r.Replace(s, "<br/>");
return s;
}