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

3

6

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

<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

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.

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?

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

Circumjacent answered 20/5, 2015 at 23:20 Comment(2)
possible duplicate of ConfigurationManager doesn't save settingsAntofagasta
The answers there didn't help. But I've figured it out now, I'll post an answer.Circumjacent
C
3

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

<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
Circumjacent answered 21/5, 2015 at 4:7 Comment(0)
M
3

Another method would be to use

My.Settings.Save()

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

Mastaba answered 21/5, 2015 at 8:17 Comment(0)
F
2

the options above is for setting not for app settings keys. I had the same problem and I solved it with the following code

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

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

    ConfigurationManager.RefreshSection("appSettings")

it is very important to save changes!!! refresh is optional (RefreshSection), if you need to immediately use the updated values

Fold answered 9/9, 2020 at 23:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.