Introduction
This article will help you to change the <appSettings>
values when you are deploying the application for the first time. At the time of application installation, we need to set application configuration parameters at the first time only. For example: When we change our database to another server, we can change Database Server Configuration Information into application Configuration file. At that time, we need to again modify the app.Config file by using our user Interface.
Background
The main purpose of this article is to Configure the application Configuration Settings. When we are Installing Windows Application, we have to update the app.Config file according to our requirements.
Using the Code
Here I have created a class that will help you to change the appSettings
value. For that, you have to use this function with two parameters UpdateAppSettings()
.
You can call this function:
AppConfigFileSettings.UpdateAppSettings("DBServerName", txtNewKeyvalue.text)
You can update appSettings
in this way:
// Class Name: AppConfigFileSettings
// Purpose: To Change appSettings Values
Imports System.Configuration
Imports System.Xml
Public Class AppConfigFileSettings
Public Shared Sub UpdateAppSettings_
(ByVal KeyName As String, ByVal KeyValue As String)
Dim XmlDoc As New XmlDocument()
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
For Each xElement As XmlElement In XmlDoc.DocumentElement
If xElement.Name = "appSettings" Then
For Each xNode As XmlNode In xElement.ChildNodes
If xNode.Attributes(0).Value = KeyName Then
xNode.Attributes(1).Value = KeyValue
End If
Next
End If
Next
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
End Sub
End Class
app.config File
<configuration>
<appSettings>
<add key="DBServerName" value="Localhost"></add>
<add key="DatabaseName" value="TestDB"></add>
<add key="DatabaseUserID" value="sa"></add>
<add key="DatabasePwd" value="sa"></add>
</appSettings>
</configuration>
Points of Interest
- Once you run this application to change the
appSettings
value, it will not affect an application until you Exit the application and run it again. - This article shows how to modify the app.config file. But how does this code help other users? - That depends on user requirements and your point of view.