Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ignores \n in a string when written in a file

Tags:

c#

I have a simple string which has '\n' in it. It is supposed to be written into a file. For eg:

var s = new StringBuilder();

s.Append("hello");
s.Append("\n");
s.Append("betty");
s.Append("is");
s.Append("my");
s.Append("\n");
s.Append("name");

string str = s.ToString();
Console.WriteLine(str);

This string prints as expected:

hello 
bettyismy
name

Now when I try to write this string in a file using the following:

var w = new StreamWriter(crcFilePath);
w.WriteLine(crcString);
w.Close();

The content of the file is:

hellobettyismyname

Any idea why it is ignoring the \n in the string.

like image 445
user2695082 Avatar asked Apr 15 '14 05:04

user2695082


1 Answers

It is probably the application or system you are using to view your file ignoring the line feed, not C# ignoring it. Instead of \n, try using System.Environment.NewLine or \r\n. See this question for info on \r and \n. Also, Notepad++ can show white space chars including new lines, which can be handy in such cases.

like image 105
xr280xr Avatar answered Oct 21 '22 05:10

xr280xr