C# 和 ASP.NET 中的换行符变体是什么?(\r\n vs.\n)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/932633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:36:59  来源:igfitidea点击:

What's with the line break variations in C# and ASP.NET? (\r\n vs.\n)

c#asp.netasp.net-mvcnewline

提问by Jeff Putz

I've been writing code for ASP.NET since the start, and today I encountered something I've never seen before. Typically I've looked for line breaks in C# (when posted in ASP.NET from a textarea, for example) by expecting "\r\n". Now I'm using the MVC framework, and the text coming over the wire from a textarea simply has "\n" for line breaks.

我从一开始就一直在为 ASP.NET 编写代码,今天我遇到了一些我以前从未见过的东西。通常,我通过期望“\r\n”在 C# 中寻找换行符(例如,当从 textarea 在 ASP.NET 中发布时)。现在我正在使用 MVC 框架,并且从 textarea 传输过来的文本只有“\n”来表示换行符。

Is there something going on in old school TextBox controls that normalizes the line breaks? Since MVC just uses the form data as-is, is this normal? Would love to get some insight.

老式 TextBox 控件中是否发生了一些使换行符正常化的事情?由于 MVC 只是按原样使用表单数据,这正常吗?很想得到一些见解。

采纳答案by User

I have made observation that the actual line break sequence differs from browser to browser.

我观察到实际的换行顺序因浏览器而异。

If you have a multiline textarea on a page and the page is submitted then:

如果页面上有一个多行 textarea 并且页面已提交,则:

IE returns "\r\n" to indicate newlines. FF returns "\n" in this case.

IE 返回 "\r\n" 以指示换行符。在这种情况下,FF 返回“\n”。

I tested it somewhere along the end of 2006, so it may be different now.

我在 2006 年底的某个地方对其进行了测试,所以现在可能有所不同。

I do not believe it could have anything to do with WebForms vs. MVC. Both just process submitted input and return it to you as it is.

我不相信它与 WebForms 与 MVC 有任何关系。两者都只是处理提交的输入并将其原样返回给您。

If you wish to somehow process and replace these characters it would make sense doing it in the long-to-short order:

如果您希望以某种方式处理和替换这些字符,那么按从长到短的顺序进行操作是有意义的:

string userText = form["Text"];
userText = userText.Replace ("\r\n", "<br/>").Replace ("\r", "<br/>");

回答by Kosi2801

\n is the line ending variant on *nix-style systems. \r\n is Windows-specific line-ending behaviour.

\n 是 *nix 风格系统上的行尾变体。\r\n 是特定于 Windows 的行结束行为。

If you're checking for line-endings and expose your interface to non-Windows environments, be sure to check not only for \r\n but also for \n alone.

如果您正在检查行尾并将您的界面暴露给非 Windows 环境,请确保不仅检查 \r\n 还单独检查 \n。

Fore more background, check out the Newlinearticle at Wikipedia.

如需更多背景信息,请查看Wikipedia 上的Newline文章。

回答by KP.

I am using Environment.NewLine:

我正在使用Environment.NewLine

string userText = form["Text"];
userText = userText.Replace (Environment.NewLine, "<br />")

Also take a look at @Haacked's post about some newline textarea quirks.

也看看@Haacked的关于一些换行文本区域怪癖的帖子。