Solved

Dynamically insert app setting key into Web.Config

Posted on 2011-03-04
3
683 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …
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…

803 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