Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Environment.NewLine and \n

Tags:

c#

.net

asp.net

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,

like image 780
Zath Avatar asked Feb 27 '14 03:02

Zath


3 Answers

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.

like image 59
Leon Bambrick Avatar answered Nov 19 '22 15:11

Leon Bambrick


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"

like image 21
SeeMoreGain Avatar answered Nov 19 '22 15:11

SeeMoreGain


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 />");
like image 5
Simon Whitehead Avatar answered Nov 19 '22 16:11

Simon Whitehead