Using Constructors with Object Oriented Database Development with VB.NET 2005 - The complete source code for working with the config file
(Page 4 of 5 )
The following is the source code used to work with the "config" file very effectively within a VB.NET application.
Imports System
Imports System.Xml.Serialization
Imports System.IO
Public Class ApplicationSettings
Private m_DBConnectionString As String = "type ConnectionString to
connect to database here"
Public Property DBConnectionString() As String
Get
Return m_DBConnectionString
End Get
Set(ByVal Value As String)
m_DBConnectionString = Value
End Set
End Property
Public Sub SaveAppSettings()
Dim myWriter As StreamWriter = Nothing
Dim mySerializer As XmlSerializer = Nothing
Try
' Create an XmlSerializer for the
' ApplicationSettings type.
mySerializer = New XmlSerializer( _
GetType(ApplicationSettings))
'myWriter = New StreamWriter(Application.LocalUserAppDataPath
+ "Application.config", False)
myWriter = New StreamWriter(APPLICATION_SETTINGS_FILEPATH +
"Application.config", False)
' Serialize this instance of the ApplicationSettings
' class to the config file.
mySerializer.Serialize(myWriter, Me)
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
' If the FileStream is open, close it.
If Not (myWriter Is Nothing) Then
myWriter.Close()
End If
End Try
End Sub
Public Function LoadAppSettings() As Boolean
Dim mySerializer As XmlSerializer = Nothing
Dim myFileStream As FileStream = Nothing
Dim fileExists As Boolean = False
Try
' Create an XmlSerializer for the ApplicationSettings type.
mySerializer = New XmlSerializer(GetType(ApplicationSettings))
'Dim fi As New FileInfo(Application.LocalUserAppDataPath +
"Application.config")
Dim fi As New FileInfo(APPLICATION_SETTINGS_FILEPATH +
"Application.config")
' If the config file exists, open it.
If fi.Exists Then
myFileStream = fi.OpenRead()
' Create a new instance of the ApplicationSettings by
' deserializing the config file.
Dim myAppSettings As ApplicationSettings = CType( _
mySerializer.Deserialize(myFileStream), _
ApplicationSettings)
' Assign the property values to this instance of
' the ApplicationSettings class.
Me.DBConnectionString = myAppSettings.DBConnectionString
fileExists = True
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
' If the FileStream is open, close it.
If Not (myFileStream Is Nothing) Then
myFileStream.Close()
End If
End Try
Return fileExists
End Function
End Class
Next: Developing a simple Data Helper >>
More Visual Basic.NET Articles
More By Jagadish Chaterjee