Add custom configuration Element at runtime
Is it possible to add an custom configuration element at runtime.
Here is my app.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="NodeList"
type="Configuration.NodeListSection, NodeListCon开发者_Python百科figuration"
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>
Can we add more nodes at runtime using C# code.
This doesn't appear to be from a built-in configuration section. You will find that "NodesList" is an section/element that is custom written. To determine where in your codebase it is coming from look for "NodesList" at the top of your config file in the configSections
element. That will point you at the class to look into.
After that, you need the class to support write operations properly.
To learn a lot more about customising configuration files there is a great series at CodeProject on the topic. In particular, the section on Saving Configuration Changes should be helpful to you.
Edit (after more info added to question):
Try something like (of course it all depends on what's in NodeListSection codebase):
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);
The file you have posted does not look like a normal .NET config file, but a custom XML file.
In either case - .config
files are just XML files - you can open, manipulate and save them using any of the XML libraries within the BCL, such as XDocument
.
However, if you want to make changes to configuration during runtime, you will need to decide whether the application should apply these changes at runtime as well and code for this, as normally a configuration file will only be read at startup.
private void AddNewKey_Config(string key, string value, string fileName)
{
var configFile = ConfigurationManager.OpenExeConfiguration(fileName);
configFile.AppSettings.Settings.Add(key, value);
configFile.Save();
}
精彩评论