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

2020-01-29 05:23发布

In my app.config I have this section

<appSettings>
    <add key ="UserId" value ="myUserId"/>
     // several other <add key>s
</appSettings>

Usually I access the values using userId = ConfigurationManager.AppSettings["UserId"]

If I modify it using ConfigurationManager.AppSettings["UserId"]=something, the value is not saved to the file, and next time I load the application, it uses the old value.

How can I change the value of some app.config keys during runtime?

4条回答
对你真心纯属浪费
2楼-- · 2020-01-29 06:11

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.

查看更多
够拽才男人
3楼-- · 2020-01-29 06:11

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);
    }
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-29 06:16

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); 
查看更多
干净又极端
5楼-- · 2020-01-29 06:18
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

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

You can read about ConfigurationManager here

查看更多
登录 后发表回答