Using Visual Studio 2010 and C#
This has worked over the many years...
string myString= txtSomeMultiLineTextBox.Text;
string str = myString.Replace(System.Environment.Newline, "<br />");
When setting a breakpoint, if myString = LineOne\nLineTwo\nLineThree
The \n is NOT replaced...
Then str = myString
There is no replace.
myString remains the same
I have researched everywhere about Environment.Newline and the differences with operating environments and the one I work with is Windows 7.
This Environment will not change.
Why is Environment.Newline not reading \n ?
Thanks,
Given that you've tagged this as asp.net
I'll assume that txtSomeMultiLineTextBox
is ultimately a TextArea
.
TextArea
returns text that is delimited either by \n
or \r\n
depending on the specific browser version. (IE used to always use \r\n
and now uses \n
, strange but true.)
So probably the reason why it used to work was because you were testing on an earlier version of IE, where \r\n
was used as the new line, whereas you're now using either IE 10, 11 or Chrome, and \n
is the newline.
So, to be tolerant of both situations do this:
myString.Replace("\r\n", "\n").Replace("\n", "<br />");
And just to clear this up once and for all:
Don't trust Environment.NewLine to solve this for you.
If your environment is Windows, then there is no single consistent new line used everywhere, even within Microsoft products. Better to be prepared to roll up your sleeves and normalise the line endings for yourself.
This is because System.Environment.Newline is composed of the carriage return and the new line character ie "\r\n"
so it does not match just `"\n"
Because Environment.NewLine
is platform dependent.
Environment.NewLine
on non-Unix (... Windows) platforms is \r\n
. That's a carriage return and line feed.
If your string contains only \n
.. then it can't replace \r\n
.. because that grouping isn't there.
As a test.. just replace the \n
..:
string myString= txtSomeMultiLineTextBox.Text;
string str = myString.Replace("\n", "<br />");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With