Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New line character in text file (C#)

I'm exporting text to a file in C# using System.IO.File.AppendAllText, and passing in the text file, and then the text I want to export with \n added to the end. When I view the text document, they are not on different lines, although that pesky return-line character is there between the lines. So the system may think it's two line, but a user sees it as one. How can this be fixed automatically without doing a find-replace every time I generate a file?

System.IO.File.AppendAllText(@"./WarningsLog.txt", line + "\n");
like image 430
Kieran Paddock Avatar asked Jan 29 '16 15:01

Kieran Paddock


2 Answers

You need to use the Environment.NewLine instead of \n, because newline can be more than that. in windows (if I'm not mistaken), the default is actually \r\n

Although, using \r\n, will help you temporary, using Environment.NewLine is the proper way to go

like image 104
user853710 Avatar answered Sep 28 '22 19:09

user853710


First off, there are a couple of ways to represent the new line. The most commonly used are:

  • The unix way - to write the \n character. \n here represents the newline character.
  • The windows way - to write the \r\n characters. \r here goes for the carriage return character.

If you are writing something platform-independent, Environment.NewLine will do the job for you and pick the correct character(s).

MSDN states it represents:

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

Also, in some cases you may want to use System.IO.File.AppendAllLines that takes an IEnumerable<string> as the lines collection and appends it to the file. It uses Environment.NewLine inside.

like image 45
bashis Avatar answered Sep 28 '22 18:09

bashis