1

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!

7
  • It depends on which platform do you plan to re-read your writes. However, unless specific requirements I would always go for Environment.NewLine Commented Dec 15, 2013 at 8:54
  • Good read about difference here, Commented Dec 15, 2013 at 8:55
  • @OndrejJanacek I did search both SO and Google, but must have somehow skimmed or just plain missed it; I cannot believe I missed something so bleeding obvious :( Commented Dec 15, 2013 at 13:09
  • @Steve cheers fro the succinct comment :) Commented Dec 15, 2013 at 13:09
  • 1
    @RohitVats that's a good explanation of a few different bits; cheers! Commented Dec 15, 2013 at 13:10

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Where "Mac" means Mac OS 9 or before .. [Mac] OS X is "Unix"
@user2864740 your little addendum to AccessDenied's answer is what got it marked as Answer; cheers both!
1

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.

1 Comment

It all came from a complete ignorance where by I did not actually know about NewLine until today :/ (still somewhat newish to .NET from other languages); cheers for the answer!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.