Saturday, February 5, 2011

In .net, what's the best / safest way to add a "end of line" character to a text file?

I assume there must be a system and language independent way to just stick the "current" EOL character into a text file, but my MSDN-fu seems to be weak today. Bonus points if there is a way to do this in a web application that will put the correct EOL character for the current client's machine's OS, not the web server's.

  • System.Environment.NewLine

    From roryf
  • Open the text file, seek to the end, and append Environment.NewLine.

    From DannySmurf
  • You are looking for Environment.NewLine. This will only be for your current operating system however.

    From Aydsman
  • For the bonus point:

    • Check the user-agent of the client machine, for substrings such as Windows, or Linux
    • The System.Environment.NewLine for Windows is 0x13, 0x10; in unix, it's generally 0x10 only;
    • Choose the appropriate newline string, append it to the line, and off you go
  • For server-side code I would go for TextWriter.WriteLine. Detecting the OS of the client's machine requires browser sniffing - check Request.Browser.

    From korchev

0 comments:

Post a Comment