Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top