views:

50

answers:

1

Is there a way of creating a new setting in the Settings.settings file during run time?

For example, I want to write to the settings file from one class function, and read that value from a different class function. And no, I don't want to pass the values.

  • I know how to get values from the Settings.settings file (value = Properties.Settings.Default.XXX)
  • I know how to update an existing value (Properties.Settings.Default.XXX = newValue; Properties.Settings.Default.Save())

I want to know how I can add "Name", "Type", "Scope" and "Value" into the Settings.settings file during run time.

Any suggestions would be appreciated!

Thanks, Ivar

+1  A: 

The Issues

I believe Visual Studio generates code when you design the application settings and values, therefore at runtime this would not be easy and at worst impossible without a designer. However you can sometimes call upon design features at runtime.

You'll notice the code-behind has the properties in C# that you create in your designer. For example, I added a setting for:

 Age [int]  30. 

The code-behind has generated:

    [global::System.Configuration.UserScopedSettingAttribute()]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Configuration.DefaultSettingValueAttribute("30")]
    public int Age {
        get {
            return ((int)(this["Age"]));
        }
        set {
            this["Age"] = value;
        }
    }

(The code generation is why you have strongly-typed settings)

I'm unsure if you could effect this same thing at runtime. You would have to generate code and feed it back to the JIT compiler dynamically or something like that. Or maybe there's another way I don't know about in my limited understanding of settings.

Suggestion/Workaround

I'd suggest figuring out an alternate/easier way instead of jumping through hoops. For example, make one setting a collection type that is serializable so it can store multiple values.

Then you can, for example, store multiple ages under just one setting:

 Ages  [System.Collections.ArrayList]  {add multiple values programatically}

You might end up with C# code to manage it like:

        System.Collections.ArrayList list = new System.Collections.ArrayList();
        list.Add("1");
        list.Add("30");
        Properties.Settings.Default.Ages = list;
        Properties.Settings.Default.Save();
John K
:( ah oh.......
topgun_ivard
yup, but for which I will need to have a predefined setting called Age added to my Settings.settings file, correct?
topgun_ivard
Yes, correct. I edited my answer with a solution.
John K