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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 11:35:49

问题


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.

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.


回答1:


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:

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

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

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.

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/>");



回答2:


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

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.

Fore more background, check out the Newline article at Wikipedia.




回答3:


I am using 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.



来源:https://stackoverflow.com/questions/932633/whats-with-the-line-break-variations-in-c-sharp-and-asp-net-r-n-vs-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!