
Image 1.
At run time we will change "Country" Key Value.
This is my XAML code
<Window x:Class="UpdateAppConfigValueInWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="350"
Width="525"
Title="Update App.config value in WPF">
<Grid>
<Button Content="Update" Click="Button_Click" Height="20" Width="70" Margin="205,77,228,214"></Button>
<TextBox Height="23" HorizontalAlignment="Left" Margin="184,34,0,0" Name="textBoxCountry" VerticalAlignment="Top" Width="120" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="79,34,0,0" Name="textBlock1" Text="New Value for Key" VerticalAlignment="Top" Width="99" />
</Grid>
</Window>
This is my XAML.vb code
Imports
System.Collections.Generic
Imports
System.Linq
Imports
System.Text
Imports
System.Windows
Imports
System.Windows.Controls
Imports
System.Windows.Data
Imports
System.Windows.Documents
Imports
System.Windows.Input
Imports
System.Windows.Media
Imports
System.Windows.Media.Imaging
Imports
System.Windows.Navigation
Imports
System.Windows.Shapes
Imports
System.Configuration
Imports
System.Xml
Class
Window1
Private Sub
Button_Click(ByVal sender
As Object,
ByVal e As
RoutedEventArgs)
If Not
String.IsNullOrEmpty(textBoxCountry.Text)
Then
UpdateConfigKey("Country",
textBoxCountry.Text)
textBoxCountry.Text = String.Empty
Else
MessageBox.Show("Please type some
value.")
End If
End Sub
Public Sub
UpdateConfigKey(ByVal strKey
As String,
ByVal newValue As
String)
Dim xmlDoc As
New XmlDocument()
xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory &
"..\..\App1.config")
If Not
ConfigKeyExists(strKey) Then
Throw
New ArgumentNullException("Key",
"<" & strKey & ">
not find in the configuration.")
End If
Dim appSettingsNode
As XmlNode = xmlDoc.SelectSingleNode("configuration/appSettings")
For Each
childNode As XmlNode In
appSettingsNode
If childNode.Attributes("key").Value
= strKey Then
childNode.Attributes("value").Value
= newValue
End If
Next
xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory &
"..\..\App1.config")
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
MessageBox.Show("Key Upated Successfullly")
End Sub
Public
Function ConfigKeyExists(ByVal strKey
As String)
As Boolean
Dim xmlDoc
As New
XmlDocument()
xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory &
"..\..\App1.config")
Dim appSettingsNode As
XmlNode = xmlDoc.SelectSingleNode("configuration/appSettings")
For Each
childNode As XmlNode In
appSettingsNode
If childNode.Attributes("key").Value
= strKey Then
Return
True
End
If
Next
Return
False
End Function
End
Class
When I run the application it will ask for new value of
key as shown below:

Image 2.
Now if we see App.config key then it is already been
updated.

Image 3.