如何使用自定义配置部分保存配置文件? [英] How do I save a configuration file with a custom configuration section?

查看:63
本文介绍了如何使用自定义配置部分保存配置文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,在运行时需要在其app/web.config中插入一个自定义部分.通常,这可以通过以下方式实现:

I have an application that at run-time needs to insert a custom section into its app/web.config. Normally this can be accomplished with something like:

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);

我在这里遇到的问题是,我要添加到配置文件中的部分需要它自己的序列化处理程序.我知道在通过简单地创建IConfigurationSectionHandler的实现来读取的配置时就可以轻松解决此问题,但是我似乎找不到真正写入配置部分本身的方法

The problem I'm running into here is that the section I'm adding to the configuration file needs its own serialization handler. I know this can easily be handled when reading the configuration by simply creating an implementation of IConfigurationSectionHandler, but I can't seem to find a way to actually write the configuration section itself.

查看 MSDN 文档,ConfigurationSection类确实具有Seri​​alizeSection/DeserializeSection方法,但是它们被标记为内部方法,不能被覆盖.我还在SectionInformation中找到了GetRawXml/SetRawXml方法,但是它们被标记为基础结构级的调用,不应由用户代码直接调用.

Looking at the MSDN documentation the ConfigurationSection class does have a SerializeSection/DeserializeSection method, but they're marked internal and cannot be overridden. I also found a GetRawXml/SetRawXml method in SectionInformation, but they're marked as infrastructure-level calls that shouldn't be invoked directly by user code.

我想做的甚至是可能的吗?似乎是一个非常简单的用例.

Is what I'm trying to do even possible? It seems like a pretty straight-forward use case.

谢谢.

推荐答案

这里是一种保存在 System.Configuration.Configuration 类中的方法.

Here is a method for saving on the System.Configuration.Configuration class.

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();

这篇关于如何使用自定义配置部分保存配置文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆