public Form1()
{
InitializeComponent();
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
}
public void AddAppSetting(string key, string value)
{
config.AppSettings.Settings.Add(key, value);
config.Save();
}
/// <summary>
/// //修改键值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void SaveAppSetting(string key, string value)
{
config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);
config.Save();
}
/// <summary>
/// //获得键值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public void GetAppSetting()
{
//return config.AppSettings.Settings[key].Value;
String str = ConfigurationManager.AppSettings["Text1"];
Console.WriteLine(str);
textBox1.Text = str;
}
/// <summary>
/// //移除键值
/// </summary>
/// <param name="key"></param>
public void DelAppSetting(string key)
{
config.AppSettings.Settings.Remove(key);
config.Save();
}
public void initdata()
{
string nb1 = "Text1";
}
public ArrayList GetXmlElements(string strElem)
{
ArrayList list = new ArrayList();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");
XmlNodeList listNode = xmlDoc.SelectNodes(strElem);
foreach (XmlElement el in listNode)
{
list.Add(el.InnerText);
}
return list;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
AddAppSetting("waeawe","1");
}
private void button1_Click(object sender, EventArgs e)
{
GetAppSetting();
}
private void button3_Click(object sender, EventArgs e)
{
SaveAppSetting("Text1", "46546");
}
代码中button1读取配置。button修改配置,第一次点击Button1的时候可以正常读取配置,点击button2以后修改值。再点button1不能读取修改后的值,只能读取修改之前的值。程序关闭以后才能读取为什么?
在读取前请先使用:
ConfigurationManager.RefreshSection("appSettings");
刷新值,该函数具体用法请参考:
如果对您有帮助,请点击采纳答案好吗,谢谢~~
app.config 中的配置是程序开始运行读取的配置文件(启动时读取配置文件),读取数据应该是存储起来了,以后再去读取的时候,都是读取存储起来的数据,如果你修改app.config配置数据需要起作用,需要重启程序。如果你想实时起作用,就自定义一个配置文件存储动态数据。