Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character encoding when retrieving from database

I have a WPF MVVM application which stores some text in a database (nvarchar). This text includes \n to indicate a new line. When I view the column in SQL Management Studio, it displays \n as expected but when the data is being retrieved using Entity Framework, it brings back \\n which causes the newline not to be displayed when I'm binding the property to my textblock.

How can I stop this behaviour?

Some additional information: The text comes back from the DB and gets assigned to a property on the viewmodel which is then bound to the textblock. If I hardcode the property to be something like "Time\nStamp", it works perfectly with the textblock displaying the data on 2 separate lines. The problem only seems to lie in Entity or the DB. I'm using SQL server 2012 btw.

like image 262
ChrisO Avatar asked Mar 22 '26 01:03

ChrisO


1 Answers

From C# Obeying the NewLine Character in a String Pulled from SQL server, when you retrieve a string from SQL, the value stored in the database is stored as a literal. When the \n is retrieved, it is read into the string value as a literal, and not a New Line escape character.

 str.Replace("\\n", Environment.NewLine); // Changes the escaped new line character to a NewLine character, environmental dependent.
like image 74
Bob. Avatar answered Mar 24 '26 16:03

Bob.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!