Solved

Dynamically insert app setting key into Web.Config

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
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…

910 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

22 Experts available now in Live!

Get 1:1 Help Now