在运行时添加自定义配置元素
是否可以在运行时添加自定义配置元素。
这是我的 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# 代码在运行时添加更多节点吗?
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, 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>
Can we add more nodes at runtime using C# code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这似乎不是来自内置配置部分。您会发现“NodesList”是自定义编写的部分/元素。要确定它来自代码库中的哪个位置,请在配置文件顶部的
configSections
元素中查找“NodesList”。这将指向您要查看的班级。之后,您需要该类正确支持写操作。
要了解有关自定义配置文件的更多信息,请参阅 CodeProject 上的精彩系列主题。特别是,关于保存配置更改的部分应该会对您有所帮助。
编辑(在问题中添加更多信息后):
尝试类似的操作(当然这完全取决于 NodeListSection 代码库中的内容):
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):
您发布的文件看起来不像普通的 .NET 配置文件,而是自定义的 XML 文件。
无论哪种情况 -
.config
文件只是 XML 文件 - 您可以使用 BCL 中的任何 XML 库打开、操作和保存它们,例如XDocument
。但是,如果您想在运行时更改配置,则需要决定应用程序是否也应在运行时应用这些更改并为此编写代码,因为通常仅在启动时读取配置文件。
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 asXDocument
.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.