Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new settings on runtime and read after restart

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

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
    var property = new SettingsProperty("Testname");
    property.DefaultValue = "TestValue";
    Settings.Default.Properties.Add(property);
    Settings.Default.Save();
}

At this point, the setting is stored and I can access it.

After restarting the application, the newly created setting is away:

public MainForm()
{
    InitializeComponent();

    foreach (SettingsProperty property in Settings.Default.Properties)
    {
          //Setting which was created on runtime before not existing
    }
}

Trying this piece: Settings.Default.Reload(); didn't affect anything on the outcome. I tried also other things like described here, but neither of them worked for me.

like image 288
eMi Avatar asked Sep 24 '14 13:09

eMi


People also ask

How do I change the Java runtime environment settings?

Click View to display the Java Runtime Environment Settings Verify that the latest Java Runtime version is enabled by checking the Enabled box. Click OK in Java Control Panel window to confirm changes and close the window.

How to force an application to use new configuration settings without restarting?

By using Options pattern, we can force our application to use the new configuration settings without restarting our website (or server). This method only relies on page refresh.

How to manage settings at runtime in WPF?

The settings are managed in WPF as XML file. If you manage the settings at runtime, you have to access the Settings.Default.Properties Within this enumeration are elements of type SettingsProperty prop = Properties.Settings.Default.Properties [property_name];

How to persist changes to the settings between application sessions?

C#. Properties.Settings.Default.myColor = Color.AliceBlue; If you want to persist the changes to the settings between application sessions, call the Save method as shown in this example: C#. Properties.Settings.Default.Save (); User settings are saved in a file within a subfolder of the user’s local hidden application data folder.


2 Answers

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

like image 148
Tom Deloford Avatar answered Oct 05 '22 06:10

Tom Deloford


Just a tiny bit later: I was having the same problem now and the answer of Tom was the only functioning hint. But since it was missing a bit of detail I want to share with you my solution for this.

using System.Configuration;

public static class ApplicationSettingsBaseExtension
    {
        public static void Add<T>(this ApplicationSettingsBase settings, string propertyName, T val)
        {

            bool itemExists = false;
            foreach (SettingsProperty property in settings.Properties)
            {
                if (property.Name == propertyName)
                {
                    itemExists = true;
                    break;
                }
            }
            if (!itemExists)
            {
                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();
            }

            settings[propertyName] = val;
            settings.Save();
        }

        public static T Get<T>(this ApplicationSettingsBase settings, string propertyName, T defaultValue)
        {
            bool itemExists = false;
            foreach (SettingsProperty property in settings.Properties)
            {
                if (property.Name == propertyName)
                {
                    itemExists = true;
                    break;
                }
            }
            if (!itemExists)
            {
                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] = defaultValue;
                settings.Save();
            }

            return (T)settings[propertyName];
        }


    }

And with that you can use:

Properties.Settings.Default.Add(settingName, settingValue);
Properties.Settings.Default.Save();
...
setting = Settings.Default.Get(settingName, "");

In my case "setting" was a string, but it should work with all base types. Note that these settings are not included in Settings.Default.Upgrade().

I hope I could help someone.

like image 31
Luy Avatar answered Oct 05 '22 05:10

Luy