Updating another applications app.config key value pair
I'm trying to modify an app.config file that is not part of my .net application. My key needs to be unique and appear under a static key (Server1 or Server2) as the other application reads these values line by line, associating the database(n) value with the server(n) value.
I cannot see a method of using the standard app.config methods against an external .config file, so I'm using the Xml Document class.
Example XML file:
<add key="server1" value="SERVER\SQL2000" />
<add key="database1" value="ggfd" />
<add key="database2" value="dvdv" />
<add key="server2" value="SERVER\SQL2005" />
<add key="database3" value="trvs" />
<add key="database4" value="tgdfs" />
<add key="database5" value="trvs" />
I can read\write new nodes:
Dim MyKey As String = "database" & No?
Dim XmlDocument As New XmlDocument
Dim XmlNode As XmlNode
Dim XmlRoot As XmlNode
Dim XmlKey As XmlNode
Dim XmlValue As XmlNode
Save_Config_Parameter = ""
XmlDocument.Load("app.config")
XmlNode = XmlDocument.DocumentElement.SelectSingleNode("/configuration/appSettings/add[@key=""" & MyKey & """]")
If XmlNode Is Nothing Then
XmlNode = XmlDocument.CreateNode(XmlNodeType.Element, "add", "")
XmlKey = XmlDocument.CreateNode(XmlNo开发者_JAVA技巧deType.Attribute, "key", "")
XmlKey.Value = MyKey
XmlNode.Attributes.SetNamedItem(XmlKey)
XmlValue = XmlDocument.CreateNode(XmlNodeType.Attribute, "value", "")
XmlValue.Value = MyValue
XmlNode.Attributes.SetNamedItem(XmlValue)
XmlRoot = XmlDocument.DocumentElement.SelectSingleNode("/configuration/appSettings")
If Not XmlRoot Is Nothing Then
XmlRoot.AppendChild(XmlNode)
Else
Save_Config_Parameter = "ERROR"
End If
Else
XmlNode.Attributes.GetNamedItem("value").Value = MyValue
End If
XmlDocument.Save("app.config")
But cannot find a method of retriving the Key to check if it exists and more importantly increment the value?
Thanks.
I think you are already on the right path here. You are looking already at methods of grabbing the elements by key, so you could increment and look to see if it was there.
Now, given the structure you are talking about, it might be better to use the "NextSibling" method to walk through the elements and keep track of what items you found, rather than querying for the specifics if the order of each key is important.
精彩评论