1、引用System.Configuration.DLL

2、引用命名空间System.Configuration和System.Web.Configuration

3、上代码

            // 使用指定的虚拟路径将 Web 应用程序配置文件作为 System.Configuration.Configuration 对象打开以允许读或写操作。
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

            //@sectionName 要返回的节的路径
            //返回指定的 System.Configuration.ConfigurationSection 对象。
            AppSettingsSection appSection = (AppSettingsSection)config.GetSection("appSettings");

            //key:   指定 key 的字符串
            //value: 指定值的字符串
            //根据提供的参数向集合中添加一个 System.Configuration.KeyValueConfigurationElement 对象
            appSection.Settings.Add("MyKey", "MyValue");
            appSection.Settings.Add("MyKey", "MyValue_New");

            //将包含在此 System.Configuration.Configuration 对象中的配置设置写入到当前的 XML 配置文件中
            config.Save();

这里要注意:在添加之前要检查Key是否已经存在,如果按上面例子中写的连续对同一个Key赋值,就会导致下面的结果

会发现值“MyValue”并未被“MyValue_New”覆盖,而是在后面追加,所以添加时一定要注意!

 

posted on 2017-09-08 11:14  田坤坤  阅读(120)  评论(0编辑  收藏  举报