12.3. Outputting a Platform-Independent EOL Character
Problem
Your application will run on more than one platform. Different platforms use different end-of-line characters. You want your code to output the correct EOL character without having to write code to handle the EOL character especially for each platform.
Solution
The .NET Framework provides the Environment.NewLine constant, which represents a newline on the given platform. This is the newline string used by all of the framework provided WriteLine methods internally (including Console, Debug, and Trace).
There are a few different scenarios in which this could be useful:
Formatting a block of text with newlines embedded within it:
// Remember to use Environment.NewLine on every block of text // we format that we want platform-correct newlines at the end of. string line; line = String.Format("FirstLine {0} SecondLine {0} ThirdLine {0}", Environment.NewLine); // Get a temp file to work with. string file = Path.GetTempFileName(); using (FileStream stream = File.Create(file)) { byte[] bytes = Encoding.Unicode.GetBytes(line); stream.Write(bytes,0,bytes.Length); } // Remove the file (Good line to set a breakpoint to examine the file // we created). File.Delete(file);You need to use a different newline character than the default one used by
StreamWriter(which happens to beEnvironment.NewLine). You can set the newline that aStreamWriterwill use once so that allWriteLinesperformed by theStreamWriteruse that newline instead of having ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access