Как изменить мои ключи App.exe.config во время выполнения?
В моем app.config у меня есть этот раздел
<appSettings>
<add key ="UserId" value ="myUserId"/>
// several other <add key>s
</appSettings>
Обычно я получаю доступ к значениям, используя userId = ConfigurationManager.AppSettings["UserId"]
Если я изменяю его с помощью ConfigurationManager.AppSettings["UserId"]=something
, это значение не сохраняется в файле, а в следующий раз, когда я загружаю приложение, оно использует старое значение.
Как я могу изменить значение некоторых ключей app.config во время выполнения?
Ответы
Ответ 1
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["UserId"].Value = "myUserId";
config.Save(ConfigurationSaveMode.Modified);
Вы можете прочитать о ConfigurationManager здесь
Ответ 2
Изменение файла 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);
}
}
Ответ 3
После изменения значения, вероятно, u не будет сохранять документ Appconfig.
// update
settings[-keyname-].Value = "newkeyvalue";
//save the file
config.Save(ConfigurationSaveMode.Modified);
//relaod the section you modified
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
Ответ 4
На боковой ноте.
Если что-то в вашем app.config необходимо изменить во время выполнения... его возможное место лучше сохранить эту переменную.
App.config используется для констант. В худшем случае что-то с однократной инициализацией.