Public Class AutoSaveConfigurationManager
    Inherits ConfigurationManager

    Private addedHandler As Boolean = False
    Private enableAutoSave As Boolean = False
    Private _ConfigFilePath As String = String.Empty
    Private _AutoLoadConfigOnAccess As Boolean = False

    Public Property ConfigFilePath As String
        Get
            Return _ConfigFilePath
        End Get
        Set
            _ConfigFilePath = Value
            If AutoLoadConfigOnAccess Then Load()
        End Set
    End Property

    Public Property AutoLoadConfigOnAccess As Boolean
        Get
            Return _AutoLoadConfigOnAccess
        End Get
        Set
            _AutoLoadConfigOnAccess = Value
            If Value Then Load()
        End Set
    End Property

    Public Property AutoSaveConfigOnExit As Boolean
        Get
            Return enableAutoSave
        End Get
        Set
            If enableAutoSave <> Value Then
                enableAutoSave = Value
                Select Case enableAutoSave
                    Case True
                        AddAutoSaveHandler()
                    Case False
                        RemoveAutoSaveHandler()
                End Select
            End If
        End Set
    End Property

    Private Sub AddAutoSaveHandler()
        If Not addedHandler Then
            AddHandler AppDomain.CurrentDomain.ProcessExit, AddressOf AutoSaveSettingsOnExit
            addedHandler = True
        End If
    End Sub

    Private Sub RemoveAutoSaveHandler()
        RemoveHandler AppDomain.CurrentDomain.ProcessExit, AddressOf AutoSaveSettingsOnExit
        addedHandler = False
    End Sub

    Private Sub AutoSaveSettingsOnExit(sender As Object, e As EventArgs)
        Save()
    End Sub

    Private Sub Save()
        If Not String.IsNullOrEmpty(ConfigFilePath) AndAlso Configuration IsNot Nothing Then
            Configuration.WriteToFile(ConfigFilePath)
        End If
    End Sub

    Private Sub Load()
        If Not String.IsNullOrEmpty(ConfigFilePath) Then
            Configuration.ReadFromFile(ConfigFilePath)
        End If
    End Sub

    Protected Overrides Sub Finalize()
        RemoveAutoSaveHandler()
    End Sub

End Class
