Create new settings on runtime and read after restart

前端 未结 1 1057
孤独总比滥情好
孤独总比滥情好 2020-12-21 00:53

I would like to store usersettings. They are created at runtime and should be read after restarting the application.

private void MainForm_FormClosing(object         


        
相关标签:
1条回答
  • 2020-12-21 01:22

    Probably a bit late for you but for others there are 2 parts.

    1. Saving the new UserSetting
    2. Reloading from userConfig.xml at startup

    I created this extension for ApplicationSettingsBase based on other answers

    public static void Add<T>(this ApplicationSettingsBase settings, string propertyName, T val)
    {           
        var p = new SettingsProperty(propertyName)
        {
            PropertyType = typeof(T),
            Provider = settings.Providers["LocalFileSettingsProvider"],
            SerializeAs = SettingsSerializeAs.Xml
        };
    
        p.Attributes.Add(typeof(UserScopedSettingAttribute), new UserScopedSettingAttribute());
    
        settings.Properties.Add(p);
        settings.Reload();
    
        //finally set value with new value if none was loaded from userConfig.xml
        var item = settings[propertyName];
        if (item == null)
        {
            settings[propertyName] = val;
            settings.Save();
        }
    }
    

    This will make Settings["MyKey"] work, but when you restart the setting will not be loaded, but the userConfig.xml has the new value (if you called Settings.Save())

    The trick to get it to reload is to execute Add again e.g

    if (settings.Properties.Cast<SettingsProperty>().All(s => s.Name != propertyName))
    {
        settings.Add("MyKey", 0);
    };
    

    The way Add works is that it will only set MyKey to 0 if no value is loaded from userConfig.xml

    0 讨论(0)
提交回复
热议问题