【问题标题】:Dynamically add and remove key-value pairs from a section in app.config从 app.config 中的部分动态添加和删除键值对
【发布时间】:2015-02-10 10:05:32
【问题描述】:

我的 XML 文件如下所示:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="databaseTypes" type="System.Configuration.NameValueSectionHandler" />
    <section name="dataDictionary" type="System.Configuration.NameValueSectionHandler" />
  </configSections>
  <databaseTypes>
    <add key="ExampleServerPrefix_T" value="Connection_String_For_ExampleServer" />
    <add key="ExampleServer2Prefix_T" value="Connection_String_For_ExampleServer_2" />
    <add key="COPYLIVE_" value="ODBC;DSN=s2;" />
  </databaseTypes>
  <dataDictionary>
    <!-- Other pairs in this section -->
  </dataDictionary>
</configuration>

我想要实现的是能够从databaseTypes 部分添加和删除键值对。因此,例如想要动态添加一个运行时一对新的&lt;add key="blah" value="ODBC;blah" /&gt;

首先知道这可能有用吗?如果是这样,怎么办,因为我找不到任何相关的文档或示例来说明这是如何完成的。

【问题讨论】:

  • 绝对有可能,我是通过实现IConfigurationSectionHandler来实现的。您是否已经定义了 databaseType 类?
  • 不,我没有定义。我需要一个吗?我只是将它用作字典。
  • 您不必这样做只是一种方法。这是一篇可能有帮助的文章:stackoverflow.com/questions/2502091/…
  • 这里还有一篇很好的文章:yizeng.me/2013/08/31/…
  • @Kevin 非常好的文章,谢谢。这篇文章部分解决了我的问题。我已经实现了它,它正在“保存”新的键值对,但它确实在保存它。新的键值对保存在内存中,直到程序完成执行它才真正写入 XML 文件。有什么想法吗?

标签: c# xml configuration app-config


【解决方案1】:

本,

这里有两篇文章可以帮助您将键/值对添加到配置中:

将自定义部分写入 app.config

Writing custom sections into app.config

在运行时更新 App.config 中的 AppSettings 和自定义配置部分

http://yizeng.me/2013/08/31/update-appsettings-and-custom-configuration-sections-in-appconfig-at-runtime/

【讨论】:

    猜你喜欢
    • 2021-06-20
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2012-01-28
    • 2019-07-11
    • 2013-12-03
    相关资源
    最近更新 更多