.NET “default line terminator”?

2019-04-18 08:04发布

问题:

Is there any way to figure out what .NET is using as its "default line terminator"? For example, documentation for StringBuilder.AppendLine(String) says it "Appends a copy of the specified string followed by the default line terminator...". Several text-related classes in .NET refer to the same concept.

Is there any way to programmatically figure out what is being used as the line terminator (at runtime)? Or is it safe to assume that it will always be "\r\n" for a Windows machine? I'd rather not hard-code that value into my code if I can avoid it.

回答1:

StringBuilder.AppendLine will use Environment.NewLine, which is "\r\n" for non-Unix platforms and "\n" for Unix platforms.

It will always be "\r\n" for a Windows machine, but you can use Environment.NewLine in lieu of a hard-coded value.

thanks to @Guffa for verifying this



回答2:

This is the code from the StringBuilder.AppendLine(string) method (using .NET Reflector):

[ComVisible(false)]
public StringBuilder AppendLine(string value)
{
   this.Append(value);
   return this.Append(Environment.NewLine);
}

As you see, it's indeed using the Environment.NewLine property.



回答3:

On Mac, the newline was '\r' that is until they based their OS on linux. Now its '\n'.