在 VB.net 中,如何保存对 app.config 的更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30361992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:08:46  来源:igfitidea点击:

In VB.net, how do I save changes to app.config

vb.netapp-configappsettings

提问by mike

I have a couple of appSettings in my app.config file, with default values:

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

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

which I am able to read and put the values into a TextBox and a ComboBox

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

I have this code to save the changes made to those two, but the changes I make are not saved to the app.config file itself, so when I close the program and open it again, the values go back to the defaults.

我有这段代码来保存对这两个所做的更改,但我所做的更改不会保存到 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

What do I need to do to get the updated values to persist to the app.config file?

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

(edit: The answers on the duplicate were not for VB and didn't solve this issue.)

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

采纳答案by mike

I didn't need to mess around with the ConfirgurationManager by changing my app.config file to this (using Solution Explorer -> My Project -> Settings)

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

<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>

I was able to use this code to save the updated values for my settings

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

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

回答by Simon Sch?dler

Another method would be to use

另一种方法是使用

My.Settings.Save()

In your ButtonSaveSettings.Click Event. Otherwise, the settings would not be retentive

在您的 ButtonSaveSettings.Click 事件中。否则,设置将不会保留