我正在尝试更改 App.Config 文件 appsettings 键值,一切正常,同时更改键值所有注释都在配置文件中删除(我也想要注释),任何人都可以帮助我我的代码有什么问题吗
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(ConfigFilepath,
ConfigurationUserLevel.None);
config.AppSettings.Settings["IPAddress"].Value = "10.10.2.3";
config.Save(ConfigurationSaveMode.Full);
Run Code Online (Sandbox Code Playgroud)
这就是我解决这个问题的方法。就我而言,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);
}
}
Run Code Online (Sandbox Code Playgroud)