Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

11.7. Outputting a Platform-Independent EOL Character

Problem

Your application will run on more than one platform. Each platform uses a different end-of-line (EOL) character. You want your code to output the correct EOL character without having to write code to handle the EOL character specially 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 when this could be useful:

  1. Formatting a block of text with newlines embedded within it:

    // 1) Remember to use Environment.NewLine on every block of text 
    // we format that we want platform correct newlines inside 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( );
    FileStream stream = File.Create(file);
    byte[] bytes = Encoding.Unicode.GetBytes(line);
    stream.Write(bytes,0,bytes.Length);
    // close the file
    stream.Close( );
    
    // remove the file (good line to set a breakpoint to check out the file
    // we created)
    File.Delete(file);
  2. 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 newline that a StreamWriter will use once so that all WriteLines performed by the StreamWriter use ...

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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata