【问题标题】:Add custom configuration Element at runtime在运行时添加自定义配置元素
【发布时间】:2018-12-04 18:19:03
【问题描述】:

是否可以在运行时添加自定义配置元素。

这是我的 app.config 文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="NodeList"
               type="Configuration.NodeListSection, NodeListConfiguration"
               requirePermission="false" />
  </configSections>
  <NodeList>
    <nodes>
      <add name="Dev1" isdefault="false" description ="Dev server" />
      <add name="QA1" isdefault="true" description="QA server"/>
      <add name="Prod1" isdefault="false" description="Production" />
    </nodes>
  </NodeList>
</configuration>

我们可以在运行时使用 C# 代码添加更多节点吗?

【问题讨论】:

  • 这看起来不像标准的 .NET 配置文件。您从哪里获得此架构?

标签: c# runtime app-config custom-configuration


【解决方案1】:

这似乎不是来自内置配置部分。您会发现“NodesList”是自定义编写的部分/元素。要确定它来自代码库中的哪个位置,请在配置文件顶部的 configSections 元素中查找“NodesList”。这会将您指向要查看的课程。

之后,您需要该类正确支持写入操作。

要了解有关自定义配置文件的更多信息,请参阅great series at CodeProject 讨论该主题。特别是Saving Configuration Changes 部分应该对您有所帮助。

编辑(在向问题添加更多信息后):

尝试类似的东西(当然这完全取决于 NodeListSection 代码库中的内容):

using Configuration;

var nodeListSection = ConfigurationManager.GetSection("NodeList") as Configuration.NodeListSection;
var newNode = new NodeElement() { Name = "xyz", IsDefault = false, Description = "New Guy" };
nodeListSection.Nodes.Add(newNode);

Configuration.Save(ConfigurationSaveMode.Modified);

【讨论】:

  • 感谢您的解决方案。我找不到 Add 方法来添加新的 NodeElement。 nodeListSection.Nodes.Add(newNode);
  • 嗯,你必须探索任何类型的“节点”来解决它。很可能它是 ConfigurationElementCollection 的派生词 - msdn.microsoft.com/en-us/library/… - 这意味着 BaseAdd 受到保护,除非显式覆盖使您的任务更加困难......
  • 我能够添加一个公共方法并将元素传递给受保护的覆盖,但保存后我看不到 App.config 文件中的更改。
  • 查看codeproject.com/KB/dotnet/mysteriesofconfiguration3.aspx#t3_1 并向下滚动一点以查看有关修改状态和Unmerge 操作的一些讨论。这可能有助于为您指明正确的方向!
【解决方案2】:

您发布的文件看起来不像普通的 .NET 配置文件,而是自定义 XML 文件。

在任何一种情况下 - .config 文件只是 XML 文件 - 您可以使用 BCL 中的任何 XML 库打开、操作和保存它们,例如 XDocument

但是,如果您想在运行时更改配置,您将需要决定应用程序是否也应在运行时应用这些更改并为此编写代码,因为通常只会在启动时读取配置文件。

【讨论】:

    【解决方案3】:
        private void AddNewKey_Config(string key, string value, string fileName)
        {
            var configFile = ConfigurationManager.OpenExeConfiguration(fileName);
            configFile.AppSettings.Settings.Add(key, value);
            configFile.Save();
        }
    

    【讨论】:

    • 您可以使用此代码在配置文件中添加新的键和值。
    猜你喜欢
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 2014-01-10
    • 2021-09-18
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多