VB • Store and Retrieve Settings

Listing 1. A custom settings provider class can help you let your users take control of how UI settings are stored and retrieved. The process itself is straightforward: Inherit from SettingsProvider and Override the GetPropertyValues function and SetPropertyValues method.

Imports System.Configuration
Imports System.Collections

Public Class FileByFileSettingsProvider
	Inherits SettingsProvider

#Region "initialize and Name property"

	Public Overrides Sub Initialize( _
		ByVal name As String, _
		ByVal config As Specialized.NameValueCollection)
		If name Is Nothing Then name = _
			My.Application.Info.ProductName
		m_appName = name
		MyBase.Initialize(m_appName, config)
	End Sub

	Private m_appName As String

	Public Overrides Property ApplicationName() _
		As String
		Get
			Return m_appName
		End Get
		Set(ByVal value As String)
			m_appName = value
		End Set
	End Property
#End Region

	' TODO: root path should be changed to the 
	' application path or similar
	Private m_rootPath As String = "E:\test\"

#Region "settings get and set values"

	Public Overrides Function GetPropertyValues( _
		ByVal context As SettingsContext, _
		ByVal properties As SettingsPropertyCollection) _
		As SettingsPropertyValueCollection

	Dim values As New SettingsPropertyValueCollection

	For Each setting As SettingsProperty In properties
		Dim filepath As String = _
			m_rootPath & setting.Name & ".xml"
		' create a SettingsPropertyValue from the setting 
		' to enable reading and writing of it
		Dim value As New SettingsPropertyValue(setting)

		With My.Computer.FileSystem
			If .FileExists(filepath) Then
				' use the SerializedValue
				value.SerializedValue = .ReadAllText(filepath)
			End If
			value.IsDirty = False
			values.Add(value)
		End With
	Next

		Return values
	End Function

	Public Overrides Sub SetPropertyValues( _
		ByVal context As SettingsContext, _
		ByVal values As SettingsPropertyValueCollection)

	For Each value As SettingsPropertyValue In values
		Dim filepath As String = m_rootPath & value.Name _
			& ".xml"
		My.Computer.FileSystem.WriteAllText(filepath, _ 
			value.SerializedValue.ToString, False)
	Next
	End Sub

#End Region

End Class