.NET “default line terminator”?

2019-04-18 07:57发布

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.

3条回答
【Aperson】
2楼-- · 2019-04-18 08:39

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楼-- · 2019-04-18 08:44

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

查看更多
放我归山
4楼-- · 2019-04-18 08:46

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

查看更多
登录 后发表回答