[英]How to modify my App.exe.config keys at runtime?
In my app.config I have this section 在我的app.config中,我有这个部分
<appSettings>
<add key ="UserId" value ="myUserId"/>
// several other <add key>s
</appSettings>
Usually I access the values using userId = ConfigurationManager.AppSettings["UserId"]
通常我使用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. 如果我使用ConfigurationManager.AppSettings["UserId"]=something
修改它,则该值不会保存到文件中,下次加载应用程序时,它会使用旧值。
How can I change the value of some app.config keys during runtime? 如何在运行时更改某些app.config键的值?
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中的某些内容需要在运行时更改...可能有更好的地方来保存该变量。
App.config is used for constants. App.config用于常量。 At worst case something with a one time initialization. 在最坏的情况下,一次初始化的东西。
After changing the value, probably u will be not saving the Appconfig document. 更改值后,可能您将不保存Appconfig文档。
// 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 修改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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.