Search code examples
c#newlineportabilitylanguage-features

Does C# have something similar to Python's universal newlines


Python's file objects can now support end of line conventions other than the one followed by the platform on which Python is running. Opening a file with the mode 'U' or 'rU' will open a file for reading in universal newline mode. All three line ending conventions will be translated to a "\n" in the strings returned by the various file methods such as read() and readline().

https://docs.python.org/2.3/whatsnew/node7.html

In Python 3, universal newlines is the default mode to open text files in. That means, when opening text files, I do not have to care about line ending conventions at all.

Do we have convenience feature like this in C#, too?


Solution

  • StreamReader.ReadLine does this:

    A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.

    The convenience methods for reading the lines out of a file, such as File.ReadLines and File.ReadAllLines, use a StreamReader under the hood.

    I don't know of any method which will read multiple lines from a file as a string, but will silently replace all line ending characters with a normalized \n however. StreamReader.ReadToEnd() doesn't manipulate the text it reads in this way.