Kieran Paddock
Kieran Paddock

Reputation: 403

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");

Upvotes: 6

Views: 30127

Answers (3)

Mihaylov
Mihaylov

Reputation: 358

You could try building this with some file specific characters checks , like new line, tab , etc.... Here is an example code which checks for new line and tabs :

 public static string Replace()
        {  
             string rLower =   words.ToLower().Replace(Environment.NewLine, "<replaced_newLine>");
            rLower = rLower.Replace("\t", "<replaced_Tabulation>");
            return rLower;
        }

Of course you might have a lot of different combinations , where an item that needs to be changed is followed by " " or "\n" or "\r\n" or "\t"

Upvotes: 0

bashis
bashis

Reputation: 1243

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.

Upvotes: 6

user853710
user853710

Reputation: 1767

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

Upvotes: 20

Related Questions