Config 连接字符串中的转义引号

在我的 web 配置中有一个连接字符串:

<add name="MyConString" connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass"word" providerName="System.Data.SqlClient" />

如您所见,密码中有一个引号(“)(由其他部门提供,我无法更改这个 db 用户密码)。

如何转义此连接字符串中的引号?

顺便说一句: 我已经在字符串中尝试过了。但这并没有起作用—— ado.net 得到了一个 ArgumenException 异常: “海斯命令集的格式不符合从索引57开始的规范。” 57是连接字符串中 & quot; 的位置。 我也试过把密码部分封起来,但也不管用。

也尝试了“”和“-web.config”,然后无法解析。

谢谢你的解决方案:

我必须将双引号的转义和密码放在单引号中结合起来:

<add name="MyConString" connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'" providerName="System.Data.SqlClient" />
121616 次浏览

Use &quot; instead of " to escape it.

web.config is an XML file so you should use XML escaping.

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

See this forum thread.

Update:

&quot; should work, but as it doesn't, have you tried some of the other string escape sequences for .NET? \" and ""?

Update 2:

Try single quotes for the connectionString:

connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass"word'

Or:

connectionString='Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word'

Update 3:

From MSDN (SqlConnection.ConnectionString Property):

To include values that contain a semicolon, single-quote character, or double-quote character, the value must be enclosed in double quotation marks. If the value contains both a semicolon and a double-quote character, the value can be enclosed in single quotation marks.

So:

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

The issue is not with web.config, but the format of the connection string. In a connection string, if you have a " in a value (of the key-value pair), you need to enclose the value in '. So, while Password=somepass"word does not work, Password='somepass"word' does.

Use &quot; That should work.

connectionString="Server=dbsrv;User ID=myDbUser;Password=somepass&quot;word"

Since the web.config is XML, you need to escape the five special characters:

&amp; -> & ampersand, U+0026
&lt; -> < left angle bracket, less-than sign, U+003C
&gt; -> > right angle bracket, greater-than sign, U+003E
&quot; -> " quotation mark, U+0022
&apos; -> ' apostrophe, U+0027

+ is not a problem, I suppose.


Duc Filan adds: You should also wrap your password with single quote ':

connectionString="Server=dbsrv;User ID=myDbUser;Password='somepass&quot;word'"

if &quot; isn't working then try &#34; instead.

Odeds answer is almost complete. Just one thing to add.

  1. Escape xml special chars like Emanuele Greco said.
  2. Put the password in single quotes like Oded said
  3. (this one is new) Escape single ticks with another single tick (ref)

having this password="'; this sould be a valid connection string:

connectionString='Server=dbsrv;User ID=myDbUser;Password='&quot;&amp;&amp;;'