Clickonce application not seeting AppSettings

时光毁灭记忆、已成空白 提交于 2019-12-06 05:15:19

I guess you are using the settings wrong.

First of all, you need to mind the difference between application and user settings. Application settings are constant and can not be changed from your code (for example default values, connection strings, etc.). User settings are for settings that change when the application runs, usually because there is some sort of Settings dialog in your application.

Secondly, you need to access them properly. People tend to (and I don't know why) use things like ConfigurationManager or other stuff to access settings. It is far easier and less error-prone to use Properties.Settings.Default.SettingName for both application and user settings.

Changing a user setting would read like this:

Properties.Settings.Default.SettingName = settingValue;
Properties.Settings.Default.Save();

The call to Save is important, as otherwise the change will not be persisted.

Thirdly: No need to change the way app.config is included in your project. By default it will be renamed to applicationname.exe.config and will always be included in your output unless you say otherwise. The same goes for the ClickOnce installation: It will be included by default. You may actually break things if you play with this or the ClickOnce deployment settings for app.config! Revert them to default and leave them alone.

Now one case where the settings will be lost and reverted to defaults is when you update your application. In this case you will have to migrate your settings from the previously installed version, otherwise the user settings will be overridden with the default values from the installation. What you do to migrate the settings is:

Define a user setting named SettingsUpgradeRequired (name doesn't really matter - should be self-explaining, however) with a default value of true in the settings designer. Then, when your application starts, you do this:

if (Properties.Settings.Default.SettingsUpgradeRequired)
{
    Properties.Settings.Default.Upgrade();
    Properties.Settings.Default.SettingsUpgradeRequired = false;
    Properties.Settings.Default.Save();
}

This makes sure a migration of the settings only occurs when required. SettingsUpgradeRequired will only be true upon the first installation (in which case Upgrade does nothing) and after an update of your application, because - as I said - by default the configuration from the ClickOnce installation will override the previous configuration until you perform the upgrade.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!