簡體   English   中英

在運行時添加自定義配置元素

[英]Add custom configuration Element at runtime

是否可以在運行時添加自定義配置元素。

這是我的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#代碼在運行時添加更多節點。

這似乎不是來自內置配置部分。 您會發現“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);
    private void AddNewKey_Config(string key, string value, string fileName)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(fileName);
        configFile.AppSettings.Settings.Add(key, value);
        configFile.Save();
    }

您發布的文件看起來不像普通的.NET配置文件,而是自定義XML文件。

在任何一種情況下 - .config文件只是XML文件 - 您可以使用BCL中的任何XML庫(如XDocument打開,操作和保存它們。

但是,如果要在運行時更改配置,則需要確定應用程序是否應在運行時應用這些更改以及此代碼,因為通常只在啟動時讀取配置文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM