Visual Studio makes it easy to add user and application scoped
settings. The settings tab on your project properties will let you add
settings at design time. You can decide the type, scope, and default
value. There may be times however when you would like to add a user
scoped property at run time. I will demonstrate how to do this.
Adding the Property:
-
Create an instance of
System.Configuration.SettingsAttributeDictionary
.
- Create an instance of
System.Configuration.UserScopedSettingsAttribute
. -
Add the
System.Configuration.UserScopedSettingsAttribute
object to the
System.Configuration.SettingsAttributeDictionary
. - Create an instance of
System.Configuration.SettingsProperty
passing the
System.Configuration.SettingsAttributeDictionary
into the contructor as
well as the property name, default value, and type. -
Add the
System.Configuration.SettingsAttributeDictionary
to the My.MySettings.Default.Properties
collection.
Example Code:
Private Sub AddProperty(ByVal propertyName As String, _
ByVal defaultValue As String, ByVal propertyType As Type)
Dim providerName As String = "LocalFileSettingsProvider"
Dim attributes As New Configuration.SettingsAttributeDictionary()
Dim attr As New Configuration.UserScopedSettingAttribute()
attributes.Add(attr.TypeId(), attr)
Dim prop As New Configuration.SettingsProperty( _
New Configuration.SettingsProperty(propertyName, propertyType, _
My.MySettings.Default.Providers(providerName), False, defaultValue, _
Configuration.SettingsSerializeAs.String, attributes, False, False))
My.MySettings.Default.Properties.Add(prop)
End Sub
Setting the Property Value:
Example Code:
My.MySettings.Default.Item(propertyName) = propertyValue
Getting the Property Value:Example Code:
My.MySettings.Default.Item(propertyName).ToString()
Accessing the Property at Next Run:
You may notice that next time you run your application that the
properties you added were not loaded automatically. Only properties
that exist in your My.MySettings.Default
object are loaded when
properties are loaded.
- Add your property.
-
Reload your
My.MySettings.Default
object.
Example Code:
AddProperty(SavedPropertyNameTextBox.Text, String.Empty)
My.MySettings.Default.Reload()