Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager.AppSettings convert "\n" to "\\n" why?

I have a AppSetting in web.config.

<add key="key" value="\n|\r"/>

When i read it by ConfigurationManager.AppSettings["key"] it gives "\\n|\\r". Why ?

like image 836
Jeevan Bhatt Avatar asked Mar 02 '12 08:03

Jeevan Bhatt


3 Answers

In the debugger, becuase the backslash is a special character used for things like tabs (\t) and line endings (\n), it has to be escaped by the use of another backslash. Hence any text that contains an actual \ will be displayed as \. If you print it out to a file or use it in any other way, you will find your string only contains the one .

This isn't ConfigurationManager doing anything.

like image 72
cjk Avatar answered Nov 10 '22 03:11

cjk


The backslash escaping syntax is only recognized inside of string literals by the C# compiler. Since your string is being read from an XML file at runtime, you need to use XML-compatible escaping (character entities) in order include those characters in your string. Thus, your app settings entry should look like the following:

<add key="key" value="&x10;|&x13;"/>

Because 10 and 13 are the hex values for linefeed and carriage return, respectively.

Like cjk said, the extra slash is being inserted by the debugger to indicate that it is seeing a literal slash and not an escape sequence.

like image 28
luksan Avatar answered Nov 10 '22 03:11

luksan


I solved the same problem with a string replacement.
Not beautful.. but works!

ConfigurationManager.AppSettings["Key"].Replace("\\n", "\n")
like image 1
Emanuele Greco Avatar answered Nov 10 '22 02:11

Emanuele Greco