ConfigurationManager.AppSettings.Settings.Add() appends value on each run

旧巷老猫 提交于 2019-12-13 18:12:57

问题


I have the following piece of code. Every time, I run the C# project the values for the app settings key gets appended.

var configSettings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configSettings.AppSettings.Settings.Add("Key", "Value");
configSettings.Save(ConfigurationSaveMode.Full, true);
ConfigurationManager.RefreshSection("appSettings");

1st run: Key: Value

2nd run: Key, Value, Value

Why are the values getting appended? I need it to start on a clean plate on each run.


回答1:


You need to check if the AppSetting already exists. If it exists, you have to update the value. If it doesn't you have to add the value.

var configSettings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configSettings.AppSettings.Settings;
if (settings["Key"] == null)
{
    settings.Add("Key", "Value");
}
else
{
    settings["Key"].Value = "NewValue";
}
configSettings.Save(ConfigurationSaveMode.Full, true);
ConfigurationManager.RefreshSection("appSettings");

AppSettings.Settings is basically a collection of key/value pairs.

Check the below MSDN documentation for more details.

https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.configuration.appsettingssection.settings(v=vs.110).aspx



来源:https://stackoverflow.com/questions/31994302/configurationmanager-appsettings-settings-add-appends-value-on-each-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!