Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

newline

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.

like image 321
MoonKnight Avatar asked Jan 17 '23 03:01

MoonKnight


1 Answers

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);
like image 85
lc. Avatar answered Jan 20 '23 13:01

lc.