更改appsettings键时删除配置文件注释

时间:2012-09-11 15:24:01

标签: c# app-config

我正在尝试更改App.Config文件appsettings键值,一切正常,同时更改键值所有注释都在配置文件中删除(我也想评论),任何人都可以帮我解决我的代码有什么问题

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ConfigFilepath,
                ConfigurationUserLevel.None);
            config.AppSettings.Settings["IPAddress"].Value = "10.10.2.3";

            config.Save(ConfigurationSaveMode.Full);

3 个答案:

答案 0 :(得分:3)

这就是我解决这个问题的方法。就我而言,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);
    }
}

答案 1 :(得分:0)

基于@Jeremy_bell 很好的答案,如果您还想添加新设置,如果不退出,您可以这样做:

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);
    }
    else
    {
        XElement el = new XElement("add");
        el.SetAttributeValue("key", key);
        el.SetAttributeValue("value", value);
        document.Root.Add(el);
        document.Save(fileName);
    }
}

我刚刚添加了这个:

else
    {
        XElement el = new XElement("add");
        el.SetAttributeValue("key", key);
        el.SetAttributeValue("value", value);
        document.Root.Add(el);
        document.Save(fileName);
    }

答案 2 :(得分:-3)

保存后调用

ConfigurationManager.RefreshSection( "appSettings" );