C# Obeying the NewLine Character in a String Pulled from SQL server

让人想犯罪 __ 提交于 2019-12-12 14:30:22

问题


All (this is back-to-basics!), I have a string of information I am pulling from SQL Server. The string is something like

Hello, my name is Frank Butcher\n\n
and I work at Watford Car lot, 
and I am 65 years old.

The message is to be pulled into a message box to provide information on a process. I read the string using

SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandTimeout = 0;
cmd.CommandText = strSQL;
strResult = cmd.ExecuteScalar().ToString();

this gets the string, but when I put this into my text box the message is displayed with \n\n not with the required double NewLine.

I have tried using

strResult = strResult.Replace("\n", Environment.NewLine);

on the string but this does not help. Am I going mental, what am I doing wrong?

Thanks for your time.


回答1:


I am assuming you have stored a literal backslash then the character "n" in the string in the database, and not a newline character. Thus you have to do the String.Replace which you are doing.

You are so close, but you need to escape your backslash:

strResult = strResult.Replace("\\n", Environment.NewLine);

Without escaping the backslash, the compiler is interpreting the \n to be a special escape sequence for a newline, so your line becomes the equivalent of "replace NewLine with NewLine" (which you have figured out does nothing).

Alternatively, you can prefix the string constant with an @ symbol, meaning to treat it as a literal:

strResult = strResult.Replace(@"\n", Environment.NewLine);


来源:https://stackoverflow.com/questions/11453016/c-sharp-obeying-the-newline-character-in-a-string-pulled-from-sql-server

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