
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Outputting a Platform-Independent EOL Character
|
693
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 check out the file
// we created).
File.Delete(file);
1. You need to use a different newline character than the default one used by
StreamWriter (which happens to be Environment.NewLine). You can set the new-
line that a
StreamWriter will use once so that all WriteLines performed by the
StreamWriter use that newline instead of having to manually do it each time:
// Set up a text writer and tell it to use a certain newline
// string.
// Get a new temp file.
file = Path.GetTempFileName( );
line = "Double spaced line";
using (StreamWriter streamWriter = new StreamWriter(file))
{
// Make this always write out double lines.
streamWriter.NewLine = Environment.NewLine + Environment.NewLine;
// WriteLine on this stream will automatically use the newly specified
// newline sequence (double newline in our case).
streamWriter.WriteLine(line);
streamWriter.WriteLine(line);
streamWriter.WriteLine(line);
}
// Remove ...