[英]How do I save a configuration file with a custom configuration section?
我有一個應用程序在運行時需要將自定義部分插入其 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);
我在這里遇到的問題是我添加到配置文件的部分需要它自己的序列化處理程序。 我知道這可以通過簡單地創建 IConfigurationSectionHandler 的實現來讀取配置時輕松處理,但我似乎無法找到一種方法來實際編寫配置部分本身。
查看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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.