ConfigurationManager 不保存设置 [英] ConfigurationManager doesn't save settings

查看:29
本文介绍了ConfigurationManager 不保存设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的代码:

Here is the code I'm using:

private void SaveConfiguration()
{
    if (txtUsername.Text != "" && txtPassword.Text != "")
    {
        ConfigurationManager.AppSettings["Username"] = txtUsername.Text;
        ConfigurationManager.AppSettings["Password"] = txtPassword.Text;

        MessageBox.Show("Su configuracion guardo exitosamente.", "Exito!");
        this.Close();
    }
    else
    {
        MessageBox.Show("Por favor lleno los campos.", "Error.");
    }
}

现在,设置被保留,但是当我关闭应用程序并按 F5 再次运行它时,这些值将恢复为输入到 app.config 文件中的值.有什么建议吗?

Now, the settings are persisted but when I close the application and press F5 to run it again, the values are reverted to what is typed into the app.config file. Any suggestions?

推荐答案

我认为你应该调用 Save 方法

I think you should call the Save method

ConfigurationManager.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

编辑

为了能够保存,您必须使用 OpenExeConfiguration 方法返回的配置对象

To be able to save you have to use a configuration object returned by the OpenExeConfiguration Method

//Create the object
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

//make changes
config.AppSettings.Settings["Username"].Value = txtUsername.Text;
config.AppSettings.Settings["Password"].Value = txtPassword.Text;

//save to apply changes
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

此处有更多参考资料ConfigurationManager Class

这篇关于ConfigurationManager 不保存设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆