c# - 如何在 App.Config 中写入 URI 字符串

标签 c# configuration windows-services uri app-config

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

我想在我的 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

最佳答案

您没有正确编码 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 );
}

关于c# - 如何在 App.Config 中写入 URI 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12685846/

相关文章:

c# - Elasticsearch中的每日新索引

c# - 使用 C# Linq 表达式自定义排序

javascript - 我如何通过 Ember 中的脚本标签提供第三方 js 库?

c++ - WTSGetActiveConsoleSessionId 返回系统 session

c# - 安装后自动启动Windows服务

c# - .Net 服务因新线程启动方法上的 FileNotFoundexception 而失败

c# - 动态对象转换的语法替代方法

c# - 取消线程任务

php - Symfony 配置默认值

git - 如何指定自定义全局 gitconfig 路径?