這是我如何解決了這個問題。就我而言,appSettings部分存儲在與web.config不同的文件中(使用configSource屬性)。
public static void SaveAppSetting(string key, string value)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
SaveUsingXDocument(key, value, config.AppSettings.ElementInformation.Source);
}
/// <summary>
/// Saves the using an XDocument instead of ConfigSecion.
/// </summary>
/// <remarks>
/// The built-in <see cref="T:System.Configuration.Configuration"></see> class removes all XML comments when modifying the config file.
/// </remarks>
private static void SaveUsingXDocument(string key, string value, string fileName)
{
XDocument document = XDocument.Load(fileName);
if (document.Root == null)
{
return;
}
XElement appSetting = document.Root.Elements("add").FirstOrDefault(x => x.Attribute("key").Value == key);
if (appSetting != null)
{
appSetting.Attribute("value").Value = value;
document.Save(fileName);
}
}
的
可能重複[ConfigurationManager中可以保留在保存XML評論()?](http://stackoverflow.com/questions/1954358/can-configurationmanager-retain-xml-comments-on-save) – hybrid2102