C# – Updating application settings in WPF application

app-configapplication-settingscwpf

I'm trying to update a value in my app.config file using the code below (the value is defined in Properties > Settings as Application scoped)

System.Configuration.Configuration configApp = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MessageBox.Show(configApp.AppSettings.Settings.Count.ToString()); //this shows 0
configApp.AppSettings.Settings["PontajAdminPwd"].Value = "dsfs";
configApp.Save(ConfigurationSaveMode.Full);

but it saying that configApp.AppSettings.Settings is empty…

This is a part of my app.config file

<applicationSettings>
    <PontajWPF.Properties.Settings>
        <setting name="PontajAdminPwd" serializeAs="String">
            <value>696W3oybVP85szuiY2Qpiw==</value>
        </setting>
    </PontajWPF.Properties.Settings>
</applicationSettings>

What am I doing wrong?

Thank you

EDIT 1: I'm in a hurry so I adopted the solution proposed here (direct file access after changing the app.config file by hand – using appSettings instead of applicationSettings):
http://www.longhorncorner.com/uploadfile/rahul4_saxena/update-app-config-key-value-at-run-time-in-wpf/

Best Answer

configApp.AppSettings.Settings.Count.ToString() this will try to read settings from <appSettings> section, not <applicationSettings>. Also the name of the file should app.config.

In your case you will need to use Properties.Settings static class, to access your settings from applicationSettings. You can try PontajWPF.Properties.Settings.Default.PontajAdminPwd

Application-scope settings are read only, and can only be changed at design time or by altering the .exe.config file in between application sessions.

User-scope settings, however, can be written at run time, just as you would change any property value. The new value persists for the duration of the application session. You can persist changes to user settings between application sessions by calling the Settings.Save method. These settings are saved in the User.config file.

Read more on MSDN

Hope this helps.

Related Topic