Search code examples
c#settings

Properties.Settings.Default.Save() does not save


[Found several related articles but none had a resolution that fixed it for me.]

I'm trying to store user-selected options between sessions of running the program. All attempts to use Properties.Settings.Default.Save() have no impact; changing a setting value is not persisted between sessions of the installed program. No exception is caught in the SettingsSave() method.

private void SettingsLoad()
{
    SettingsLoad(this);
}

private void SettingsSave()
{
    try
    {
        SettingsSave(this);
        MessageBox.Show("Values written successfully", "Saved");
    }
    catch (Exception ex)
    {
       MessageBox.Show(Utility.ParseException(ex), "EXCEPTION!");
    }
}
....

public static void SettingsLoad(object main)
{
    foreach (SettingsProperty setting in Properties.Settings.Default.Properties)
    {
        // Attempt to get a reference to the property and, if found, set its value
        var prop = main.GetType().GetProperty(setting.Name);
        if (prop != null)
        {
            prop.SetValue(main, setting.DefaultValue);
        }
    }
}

public static void SettingsSave(object main)
{
    foreach (SettingsProperty setting in Properties.Settings.Default.Properties)
    {
        // Attempt to get a reference to the property and, if found, update its value
        var prop = main.GetType().GetProperty(setting.Name);
        if (prop != null)
        {
            setting.DefaultValue = prop.GetValue(main).ToString();
        }
    }
    // This line has no impact; changes are not persisted
    Properties.Settings.Default.Save();
}

Solution

  • I find your code a bit confusing.

    To read a property:

    string val = Properties.Settings.Default.Property_Name;
    

    To write a property:

    Properties.Settings.Default.Property_Name = val;
    

    To save all properties:

    Properties.Settings.Default.Save
    

    Property values will be restored next time you run the program.