christophrus
christophrus

Reputation: 1180

How can I save a copy of Properties.Settings.Default to a variable?

I have a "Restore Defaults" button in an options dialog and want to restore the values that are affected in this form only and not the whole Properties.Settings.Default

So I tried:

var backup = Properties.Settings.Default;
Properties.Settings.Default.Reload();
overwriteControls();
Properties.Settings.Default = backup;

But this unfortunately doesn't work since backup seems to change at Reload(), too? Why and how would I do this correctly?

Upvotes: 3

Views: 2354

Answers (1)

craftworkgames
craftworkgames

Reputation: 9957

The Settings class uses a singleton pattern, meaning their can only ever be one instance of the settings at any one time. So making a copy of that instance will always refer to the same instance.

In theory, you could iterate over each of the properties in the Settings class using reflection and extract the values like this:

        var propertyMap = new Dictionary<string, object>();

        // backup properties
        foreach (var propertyInfo in Properties.Settings.Default.GetType().GetProperties())
        {
            if (propertyInfo.CanRead && propertyInfo.CanWrite && propertyInfo.GetCustomAttributes(typeof(UserScopedSettingAttribute), false).Any())
            {
                var name = propertyInfo.Name;
                var value = propertyInfo.GetValue(Properties.Settings.Default, null);
                propertyMap.Add(name, value);
            }
        }

        // restore properties
        foreach (var propertyInfo in Properties.Settings.Default.GetType().GetProperties())
        {
            if (propertyInfo.CanRead && propertyInfo.CanWrite && propertyInfo.GetCustomAttributes(typeof(UserScopedSettingAttribute), false).Any())
            {
                var value = propertyMap[propertyInfo.Name];
                propertyInfo.SetValue(Properties.Settings.Default, value, null);                    
            }
        }

Although, it's a bit icky, and might need some work if your settings are complex. You might want to rethink your strategy. Rather than restoring the values to defaults, you could only commit the values once the OK button is pressed. Either way, I think you are going to need to copy each of the values to some temporary location on a property by property basis.

Upvotes: 6

Related Questions