【问题标题】:In VB.net, how do I save changes to app.config在 VB.net 中,如何保存对 app.config 的更改
【发布时间】:2015-08-02 10:16:07
【问题描述】:

我的 app.config 文件中有几个 appSettings,具有默认值:

<appSettings>
  <add key="Foo" value="one"/>
  <add key="Bar" value="two"/>
</appSettings>

我能够读取并将值放入 TextBox 和 ComboBox

我有这段代码来保存对这两个所做的更改,但我所做的更改不会保存到 app.config 文件本身,所以当我关闭程序并再次打开它时,值会恢复为默认值.

Private Sub ButtonSaveSettings_Click(sender As Object, e As EventArgs) Handles ButtonSaveSettings.Click
    Dim settings = System.Configuration.ConfigurationManager.AppSettings

    settings.Set("Foo", TextBoxFoo.Text)
    settings.Set("Bar", ComboBoxBar.SelectedItem.ToString)
End Sub

我需要怎么做才能使更新的值保留到 app.config 文件中?

(编辑:副本上的答案不适用于 VB,也没有解决这个问题。)

【问题讨论】:

标签: vb.net app-config appsettings


【解决方案1】:

以上选项用于设置,而不是应用设置键。 我有同样的问题,我用下面的代码解决了它

    Dim config As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

    config.AppSettings.Settings("yourKeyName").Value = YourNewValue        
    
    config.Save(ConfigurationSaveMode.Modified) 

    ConfigurationManager.RefreshSection("appSettings")

保存更改非常重要!!! 如果需要立即使用更新后的值,则刷新是可选的(RefreshSection)

【讨论】:

    【解决方案2】:

    另一种方法是使用

    My.Settings.Save()
    

    在您的 ButtonSaveSettings.Click 事件中。否则,设置将无法保持

    【讨论】:

      【解决方案3】:

      我不需要通过将我的 app.config 文件更改为这个(使用解决方案资源管理器 -> 我的项目 -> 设置)来搞乱配置管理器

      <userSettings>
          <MyProject.My.MySettings>
              <setting name="Foo" serializeAs="String">
                  <value>one</value>
              </setting>
              <setting name="Bar" serializeAs="String">
                  <value>two</value>
              </setting>
          </MyProject.My.MySettings>
      </userSettings>
      

      我能够使用此代码为我的设置保存更新的值

      Private Sub ButtonSaveSettings_Click(sender As Object, e As EventArgs) Handles ButtonSaveSettings.Click
          My.Settings.Foo = TextBoxFoo.Text
          My.Settings.Bar = ComboBoxBar.SelectedItem.ToString
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2016-03-25
        • 1970-01-01
        • 1970-01-01
        • 2016-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-30
        • 1970-01-01
        相关资源
        最近更新 更多