如何在运行时修改我的App.exe.config键?
在我的app.config中,我有这个部分
// several other s
通常我使用userId = ConfigurationManager.AppSettings["UserId"]
访问值
如果我使用ConfigurationManager.AppSettings["UserId"]=something
修改它,则该值不会保存到文件中,下次加载应用程序时,它会使用旧值。
如何在运行时更改某些app.config键的值?
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.Settings["UserId"].Value = "myUserId"; config.Save(ConfigurationSaveMode.Modified);
您可以在此处阅读有关ConfigurationManager的信息
在旁注。
如果app.config中的某些内容需要在运行时更改…可能有更好的地方来保存该变量。
App.config用于常量。 在最坏的情况下,一次初始化的东西。
更改值后,可能您将不保存Appconfig文档。
// update settings[-keyname-].Value = "newkeyvalue"; //save the file config.Save(ConfigurationSaveMode.Modified); //relaod the section you modified ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
修改app.config文件
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); } }