In .net, what's the best / safest way to add a “end of line” character to a text file?
-
02-07-2019 - |
Question
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.
Solution
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
OTHER TIPS
Open the text file, seek to the end, and append Environment.NewLine.
You are looking for Environment.NewLine
. This will only be for your current operating system however.
For server-side code I would go for TextWriter.WriteLine. Detecting the OS of the client's machine requires browser sniffing - check Request.Browser.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow