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

安稳与你 提交于 2019-12-11 13:14:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/20682045/how-do-i-add-a-new-property-to-properties-settings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!