ConfigurationManager.AppSettings.Settings.Add() ap

2019-07-28 23:14发布

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条回答
Emotional °昔
2楼-- · 2019-07-28 23:49

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

查看更多
登录 后发表回答