user2545571
user2545571

Reputation:

How do I add a new Property to Properties.Settings?

I want to add a new Property to Properties.Settings at runtime, but I don't know how this works. Language: c# I used this Code:

Properties.Settings.Default.Properties.Add(new System.Configuration.SettingsProperty(serviceName + "VersionsNr"));
Properties.Settings.Default.Save();

Properties.Settings.Default[serviceName + "VersionsNr"] = versionsNr;
Properties.Settings.Default.Save();

I get an NullReferenceException.

Upvotes: 1

Views: 5458

Answers (1)

Eugene
Eugene

Reputation: 2908

It's not enough to set property name. You should also define at least property attributes and setting provider. The simplest method to set this info is to use the information from existing property. For example, if you already use Settings that read/store properties values from file and you also intend use the configuration file the solution will be as follows:

        var existingProperty = Settings.Default.Properties["<existing_property_name>"];
        var property = new System.Configuration.SettingsProperty(
            "<new_property_name>",
            typeof(string),
            existingProperty.Provider,
            false,
            null,
            System.Configuration.SettingsSerializeAs.String,
            existingProperty.Attributes,
            false,
            false);
        Settings.Default.Properties.Add(property);

In the case you need something new, you can find sample code here.

Upvotes: 2

Related Questions