Monday, June 18, 2012

Reading Config File

Imports System.Windows
Imports System.Collections.Generic
Imports System.Windows.Resources
Imports System.IO
Imports System.Xml.Linq
Imports System.Reflection

'''

''' Access appSettings from a configuration file
'''

''' Your appConfig file must be in the root of your applcation
Public NotInheritable Class ConfigurationManager

    Shared Sub New()
        AppSettings = New Dictionary(Of String, String)()
        ReadSettings()
    End Sub

    Public Shared Property AppSettings() As Dictionary(Of String, String)
        Get
            Return m_AppSettings
        End Get
        Set(ByVal value As Dictionary(Of String, String))
            m_AppSettings = value
        End Set
    End Property
    Private Shared m_AppSettings As Dictionary(Of String, String)

    Private Shared Sub ReadSettings()

        Try
            ' Get the name of the executing assemby - we are going to be looking in the root folder for
            ' a file called app.config
            Dim assemblyName As String = Assembly.GetExecutingAssembly().FullName
            assemblyName = assemblyName.Substring(0, assemblyName.IndexOf(","c))
            '  Dim url As String = [String].Format("{0};component/Configuration/app.config", assemblyName)
            Dim url As String = [String].Format("{0};component/ServiceReferences.ClientConfig", assemblyName)
            Dim configFile As StreamResourceInfo = Application.GetResourceStream(New Uri(url, UriKind.Relative))
            If configFile IsNot Nothing AndAlso configFile.Stream IsNot Nothing Then
                Dim stream As Stream = configFile.Stream
                Dim document As XDocument = XDocument.Load(stream)
                For Each element As XElement In document.Descendants("appSettings").DescendantNodes()
                    AppSettings.Add(element.Attribute("key").Value, element.Attribute("value").Value)
                Next
            End If
        Catch ex As Exception

        End Try

    End Sub
End Class

No comments: