Ali Elmi
Ali Elmi

Reputation: 386

Why Notepad++ shows Carriage return + Line feed for both \r and \n

In C# define 4 variable as below:

string s1 = "\r";
string s2 = "\n";
string CarriageReturn = (Convert.ToChar(13)).ToString();
string LineFeed = (Convert.ToChar(10)).ToString();

Then by watching copy their value in Notepad++ and click on "Show all characters". Interestingly you can see there is no difference between \r and \n and for both of them, it shows CR LF. Is it a bug or something else? How can we explain this?

Upvotes: 1

Views: 2179

Answers (1)

Shaun Luttin
Shaun Luttin

Reputation: 141542

Interestingly you can see there no difference with \r and \n and for both of them it shows CR LF Is it a bug or something else?

It is not a bug. CRLF is the default for the Environment.NewLine in Windows: a 'string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.'

How can we explain this?

It probably results from the way you are outputting the string values to a file. If you use a method that adds new lines, such as WriteAllLines() does, then there will automatically be a CRLF at the end of each value you write.

For instance, we can run the following program.

string r = "\r";
string n = "\n";
string CarriageReturn = (Convert.ToChar(13)).ToString();
string LineFeed = (Convert.ToChar(10)).ToString();

var content = new string[] {
    $"(r:{r})", 
    $"(n:{n})", 
    $"(13:{CarriageReturn})", 
    $"(10:{LineFeed})" 
};

System.IO.File.WriteAllLines("output1.txt", content);
System.IO.File.WriteAllText("output2.txt", string.Join("", content));

It produces two output files. The one on the left used WriteAllLines to write four lines. The one on the right used WriteAllText() and did not write any new lines.

enter image description here

In both, all of the content outside parentheses is independent of your code. That is, the CRLF symbols are part of writing a line in the call to WriteAllLines.

Upvotes: 1

Related Questions