0

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

这是我的 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# 代码添加更多节点吗?

4

3 回答 3

2

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

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

要了解有关自定义配置文件的更多信息,CodeProject上有一个关于该主题的精彩系列。特别是,保存配置更改部分应该对您有所帮助。

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

尝试类似(当然这完全取决于 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);
于 2011-09-19T21:16:07.230 回答
0

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

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

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

于 2011-09-19T21:11:00.470 回答
0
    private void AddNewKey_Config(string key, string value, string fileName)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(fileName);
        configFile.AppSettings.Settings.Add(key, value);
        configFile.Save();
    }
于 2018-12-04T10:19:03.723 回答