C# \n, \r\n or Environment.NewLine

2.5k views Asked by At

As the heading implies, would I be best to use \n, \r\n or System.Environment.NewLine for line breaks in my C# applications?

I have a console, WinForms and WPF app which at present all use \n (where required), but in my console app I have found that when redirecting output from the CLi and open the output in Notepad the line breaks are not correctly recognised. I could just alter my behaviour for this one app but I am seeking the advice of those who consistently use a particular method and why.

Cheers!

Update:

So the general consensus is that use System.Environment.NewLine unless a specific requirement arises which needs \n (Unix/OS X), \r (OS 9) or \r\n (Windows)

Thanks all and sorry about the dup!

2

There are 2 answers

2
Kurubaran On BEST ANSWER

Better use Environment.NewLine because \r and \n are platform dependant.

\n is Unix, \r is Mac, \r\n is Windows

Environment.NewLine would return any of the above based on the operating system.

1
Will Dean On

It will always, unless you're intentionally writing a 'foreign' file, be best to use Environment.NewLine - that's what it's there for. As you've discovered, sometime you can get away with other things, sometimes you can't.

It's very easy to write code which reads text files so that it doesn't really care what combination of \n and \r are used to end lines, but as you've discovered, Notepad is strict on this.