问题
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