如何保存具有自定义配置部分的配置文件

本文关键字:配置部 自定义 配置文件 何保存 保存 | 更新日期: 2023-09-27 18:06:28

我有一个应用程序,在运行时需要插入一个自定义节到它的app/web.config。通常,这可以通过以下命令来完成:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var mySection = new MyCustomSection { SomeProperty="foo" };
config.Sections.Add("mySection", mySection);
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Full);

我在这里遇到的问题是,我要添加到配置文件的部分需要自己的序列化处理程序。我知道当读取配置时,通过简单地创建iconconfigurationsectionhandler的实现可以轻松处理,但我似乎找不到一种方法来实际编写配置部分本身。

查看MSDN文档,ConfigurationSection类确实有一个SerializeSection/DeserializeSection方法,但它们被标记为内部方法,不能被重写。我还在SectionInformation中发现了GetRawXml/SetRawXml方法,但是它们被标记为基础设施级别的调用,不应该由用户代码直接调用。

我想做的事情可能吗?这似乎是一个非常直接的用例。

谢谢。

如何保存具有自定义配置部分的配置文件

这是一个保存System.Configuration.Configuration类的方法。

System.Configuration.Configuration configRoot = null;
if(HttpContext.Current!=null)
    configRoot = WebConfigurationManager.OpenWebConfiguration(_urlRoot);
else
   configRoot = ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.PerUserRoamingAndLocal);
ConfigurationSectionGroup configGroup = configRoot.GetSectionGroup("mySections");
foreach (ConfigurationSection configSection in configGroup.Sections)
{
    //Do some updating that needs to be saved.
}
configRoot.Save();