1

我正在尝试更改 App.Config 文件 appsettings 键值,一切正常,同时更改键值时,配置文件中的所有注释都已删除(我也想要注释),谁能帮助我我的代码有什么问题

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

            config.Save(ConfigurationSaveMode.Full);
4

3 回答 3

4

这就是我解决这个问题的方法。就我而言,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);
    }
}
于 2013-05-15T15:00:31.037 回答
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);
    }
于 2021-01-27T14:38:35.293 回答
-3

保存后最后调用

ConfigurationManager.RefreshSection( "appSettings" );
于 2012-09-11T15:30:13.583 回答