Solved

Dynamically insert app setting key into Web.Config

Posted on 2011-03-04
3
686 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

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…
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
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…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

752 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