How to modify my App.exe.config keys at runtime?

≡放荡痞女 提交于 2019-11-27 13:56:19
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["UserId"].Value = "myUserId";     
config.Save(ConfigurationSaveMode.Modified);

You can read about ConfigurationManager here

On a side note.

If something in your app.config needs to change at runtime...its possible there's a better place to keep that variable.

App.config is used for constants. At worst case something with a one time initialization.

After changing the value, probably u will be not saving the Appconfig document.

// update    
  settings[-keyname-].Value = "newkeyvalue"; 
//save the file 
  config.Save(ConfigurationSaveMode.Modified);   
//relaod the section you modified 
  ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); 

Modifying app.config File

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Configuration;
using System.Xml;

public class AppConfigFileSettings
{


    public static void UpdateAppSettings(string KeyName, string KeyValue)
    {
        XmlDocument XmlDoc = new XmlDocument();

        XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

        foreach (XmlElement xElement in XmlDoc.DocumentElement) {
            if (xElement.Name == "appSettings") {

                foreach (XmlNode xNode in xElement.ChildNodes) {
                    if (xNode.Attributes[0].Value == KeyName) {
                        xNode.Attributes[1].Value = KeyValue;
                    }
                }
            }
        }
        XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!