如何在App.Config中编写URI字符串

39

我正在制作一个Windows服务。这个服务每晚都要下载一些东西,因此我想在App.Config中放置URI,以防以后需要更改它。

我想在我的App.Config中编写一个URI。什么会使它无效,我应该如何解决?

<appSettings>
    <add key="fooUriString" 
         value="https://foo.bar.baz/download/DownloadStream?id=5486cfb8c50c9f9a2c1bc43daf7ddeed&login=null&password=null"/>
</appSettings>

我的错误:

- Entity 'login' not defined
- Expecting ';'
- Entity 'password' not defined
- Application Configuration file "App.config" is invalid. An error occurred

2
只需要转义&符号即可。 - Iarek
3个回答

77

你没有正确地对URI中的&进行编码。请记住,app.config是一个XML文件,因此您必须遵守XML的转义要求(例如,&应该是&amp;< 应该是 &lt;,而> 应该是&gt;)。

在你的情况下,应该像这样:

<appSettings>
    <add
        key="fooUriString" 
        value="https://foo.bar.baz/download/DownloadStream?id=5486cfb8c50c9f9a2c1bc43daf7ddeed&amp;login=null&amp;password=null"
    />
</appSettings>

但一般来说,如果你想要存储一个类似于"I <3 angle bra<kets & ampersands >>>"的字符串,那么可以这样做:

<appSettings>
    <add
        key="someString"
        value="I &lt;3 angle bra&lt;kets &amp; ampersands &gt;&gt;&gt;"
    />
</appSettings>

void StringEncodingTest() {
    String expected = "I <3 angle bra<kets & ampersands >>>";
    String actual   = ConfigurationManager.AppSettings["someString"];
    Debug.Assert.AreEqual( expected, actual );
}

1
谢谢你们的回答。你们的回答最早,所以等几分钟后SO允许我这样做时,我会接受你们的回答。 - radbyx

9

8
尝试使用:&amp; 替代 & 在url中。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接