I'm trying to write a text file with Unix-style newlines with my C# program.
For some reason the following code doesn't work:
TextWriter fileTW = ...
fileTW.NewLine = "\n";
fileTW.WriteLine("Hello World!");
Neither does this:
TextWriter fileTW = ...
fileTW.Write("Hello World! + \n");
In both cases the '\n' is being replaced with '\r\n', which I don't want! I've been verifying this with a hex editor, which shows each line ending in 0x0D0A.
Any ideas?
Thanks!
EDIT:
Sorry everyone, false alarm!
Allow me to explain...
My TextWriter was writing to a MemoryStream, which was then being added to a tar archive using SharpZLib. It turns out that by extracting the text file using WinZIP, it was replacing every instance of \n with \r\n. If I copy the same tar archive to my Ubuntu machine and extract there, only the \n is there. Weird!
Sorry if I wasted anyone's time! Thanks!
I'm unable to reproduce this. Sample code:
Afterwards:
Note the size - 6 bytes - that's 5 for "Hello" and one for the "\n". Without setting the
NewLine
property, it's 7 (two for "\r\n").Can you come up with a similar short but complete program demonstrating the problem? How are you determining that your file contains "\r\n" afterwards?
I'm in the same boat as Jon Skeet. Here's my tests against a MemoryStream that confirm it does use what you give it as the NewLine value.
Feel free modify one of these and update your answer with your scenario.