从后面的代码更新appSettings

时间:2013-12-25 06:32:51

标签: vb.net web-config

我试图从后面的代码更新键值,似乎更新了web.config但是没有保存值。 appSetting没有什么特别的:

 <appSettings>
    <add key="Default" value="1.11"/>
    <add key="Company" value="1.078"/>
    <add key="Customer" value="1.1"/>
  </appSettings>

以下是必须更新appSettings键值的代码:

 Protected Sub btnSaveDefault_Click(sender As Object, e As System.EventArgs) Handles btnSaveDefault.Click
        Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration("/")
        config.AppSettings.Settings.Item("Default").Value = tbDefault.Text
        config.Save(ConfigurationSaveMode.Modified)
        ConfigurationManager.RefreshSection("appSettings")
    End Sub

2 个答案:

答案 0 :(得分:0)

希望这有帮助...

System.Configuration.Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");   

    objConfig.AppSettings.Settings["DEFAULT_PASSWORD"].Value = password;
    objConfig.Save();

点击此链接.. Getting error while changing Appsettings value in Web config from code behind

答案 1 :(得分:0)

好。我自己找到了解决方案问题出在另一段代码中。 因此,每次在页面加载代码上给我旧的值,如果Page.IsPostBack修复了这个问题。

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            tbCompany.Text = Convert.ToSingle(ConfigurationManager.AppSettings("Company"))
            tbDefault.Text = Convert.ToSingle(ConfigurationManager.AppSettings("Default"))
            tbUser.Text = Convert.ToSingle(ConfigurationManager.AppSettings("Customer"))
        End If
    End Sub