Recent Posts

Wednesday, September 2, 2009

How to Update App.config during runtime from .net 1.0 or .net 2.0 application?

If you want your .net 1.0 or .net 2.0 application to update app.config file during runtime then below code solves your problem. If you want to change certain settings after user logs in to your system like for eg. last login username then this code will be very helpful.

Lets look visual basic code to update app.config file in .net 2.0

Private Sub UpdateAppConfig()
Dim config As System.Configuration.Configuration = _
Dim oldValue As String
Dim newValue As String

oldValue = config.AppSettings.Settings("LastUserID").Value

If oldValue = "" Then
'do anything you like
End If

newValue = "NewUser"

'You can add a new value or remove like below just play around
config.AppSettings.Settings.Add("NewKey", "1234")
' enter new values to the config file
config.AppSettings.Settings("LastUserID").Value = newValue
' save the config file
' Now force to refresh the configuration file in the application

End Sub

Similarly lets look visual basic code to update app.config file in .net 1.0

Since .net 1.0 does not have the facility to directly save the config files as done above we have to individually go through the xml nodes of the config file and update it See below for the full function that updates the file:

Private Sub UpdateAppSetting()
Dim xmlDoc As New Xml.XmlDocument
Dim strkey As String = "LastUserID"
Dim strValue As String = "234324"
' load the file from the system where it is located
Dim element As Xml.XmlElement

For Each element In xmlDoc.DocumentElement
'check if it is appsettings or not
If element.Name.Equals("appSettings") Then
Dim node As Xml.XmlNode
For Each node In element.ChildNodes
' update the key with the value provided above
If node.Attributes(0).Value.Equals(strkey) Then
node.Attributes(1).Value = strValue
End If
End If

End Sub

Related Posts by Categories

No comments:

Post a Comment