(from comments)
actual it contains a slash n
and
it returns a 92
(where "it" is the character code at the index of the ...\n...
, so: a slash)
If the contents are a slash and an n, then: that isn't a newline, and the tools are doing the correct thing by representing it as a slash and an n. The \n
syntax only applies to C# literals, as a way of telling the compiler to include something that isn't actually a slash and an n.
A C# literal expressed as "foo\nbar"
is the string with contents:
foo
bar
(a newline)
However, a string with contents foo\nbar
is the string with contents:
foo\nbar
(a slash and an n, no newlines)
For completeness, there's also C# verbatim string literals, expressed as @"foo\nbar"
which is also the string with contents
foo\nbar
(a slash and an n, no newlines)
When you load a string
value from the database, you aren't using C# literals - you are just dealing with strings. So a slash and an n means: a slash and an n. Not a newline.
So: if possible, store what you actually mean. The text in the database should contain a newline, not a slash and an n. If the line-breaks don't show as line breaks when you do select TheValue from TheTable
, it isn't stored correctly.
If that isn't an option, you'll have to use some kind of text replace (maybe .Replace(@"\r\n","\r\n").Replace(@"\n", "\n").Replace(@"\r", "\r")
), but you'll need to think about false positives, especially if your context can include things like code examples, i.e. slash followed by n is likely to appear to mean a slash followed by n.
In terms of SQL literals; if you wanted to do this in SQL, SQL literals allow newlines directly, so:
declare @someString nvarchar(200) = N'foo
bar'; -- this contains a newline
(although whether it contains CR, LF, CRLF or LFCR may depend on your editor's line-endings)
However, usually you would be populating values by SQL parameters, i.e.
cmd.CommandText = "... @val ..."; // some SQL
cmd.Parameters.AddWithValue("@val", someStringThatHasNewlines);
cmd.ExecuteNonQuery();
where someStringThatHasNewlines
contains newline characters (ASCII 10/13), not slash+n.