Solved

Dynamically insert app setting key into Web.Config

Posted on 2011-03-04
3
680 Views
Last Modified: 2012-05-11
I have an example I found of modifying a web.config appsetting key at runtime.

Is there a way to ADD a new key through vb?
Dim xdoc As XDocument = XDocument.Load(docName)


        Dim element As XElement = xdoc.Element("configuration").Element("appSettings")
        Dim list As IEnumerable(Of XElement) = element.Descendants()


        For Each item As XElement In list
            If item.Name = "add" Then
                If item.FirstAttribute.Value = "hello" Then
                    item.LastAttribute.Value = Me.txtConfigBox.Text
                End If
            End If
        Next


        Dim writer As New XmlTextWriter(docName, Nothing)
        writer.Formatting = Formatting.Indented
        xdoc.WriteTo(writer)
        writer.Flush()
        writer.Close()

Open in new window

0
Comment
Question by:lrbrister
  • 2
3 Comments
 
LVL 18

Expert Comment

by:UnifiedIS
ID: 35040283
The app config file is just text so you can use a streamreader and streamwriter to manipulate whatever you want.  It's not advisable to change the config though.  
0
 

Accepted Solution

by:
lrbrister earned 0 total points
ID: 35040328
UnifiedIS:
This is just for me and my team in a development environment.

I found what I needed though with a button click event...see my code.
Protected Sub btnAddKey_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddKey.Click
        AddKey(txtKey.Text, txtValue.Text)
    End Sub

    Dim FileLocation As String = Server.MapPath("web.config")
    Dim NodeLocation As String = "configuration/appSettings"

    'Adds a key and value to the configuration file 
    Public Function AddKey(ByVal strKey As String, ByVal strValue As String) As Boolean
        Dim xmlDoc As New XmlDocument
        'Change this to the location of your configuration file 
        xmlDoc.Load(FileLocation)
        'Change this if node is different 
        Dim appSettingsNode As XmlNode = xmlDoc.SelectSingleNode(NodeLocation)
        Try
            'Check if the node exists before adding it 
            If (KeyExists(strKey)) Then
                Throw New ArgumentException("Key name: <" + strKey + "> already exists in the configuration.")
            End If
            'You must have at least one key that can be empty 
            Dim newChild As XmlNode = appSettingsNode.FirstChild.Clone
            newChild.Attributes("key").Value = strKey
            newChild.Attributes("value").Value = strValue
            appSettingsNode.AppendChild(newChild)
            xmlDoc.Save(FileLocation)
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function

    'Determines if a key exists 
    Public Function KeyExists(ByVal strKey As String) As Boolean
        Dim xmlDoc As New XmlDocument
        xmlDoc.Load(FileLocation)
        Dim appSettingsNode As XmlNode = xmlDoc.SelectSingleNode(NodeLocation)
        Dim childNode As XmlNode
        For Each childNode In appSettingsNode
            If (childNode.Attributes("key").Value = strKey) Then
                Return True
            End If
        Next
        Return False
    End Function

Open in new window

0
 

Author Closing Comment

by:lrbrister
ID: 35115344
Found my own solution
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

For a while now I'v been searching for a circular progress control, much like the one you get when first starting your Silverlight application. I found a couple that were written in WPF and there were a few written in Silverlight, but all appeared o…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now