ConfigurationManager.AppSettings.Settings.Add()在每次运行时附加值 [英] ConfigurationManager.AppSettings.Settings.Add() appends value on each run

查看:167
本文介绍了ConfigurationManager.AppSettings.Settings.Add()在每次运行时附加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码。每次运行C#项目时,都会附加应用设置键的值。

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.

推荐答案

您需要检查AppSetting是否已经存在。如果存在,则必须更新该值。

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 基本上是键/值对。

查看以下MSDN文档以获取更多详细信息。

Check the below MSDN documentation for more details.

https://msdn.microsoft.com/zh-我们/库/system.configuration.configurationmanager.appsettings(v=vs.110).aspx

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

这篇关于ConfigurationManager.AppSettings.Settings.Add()在每次运行时附加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆