我是如何动态编辑App.config的!

在工作中为了实现临时保存数据的目的,我选择了用App.config

本文假设App.config的预先设置内容如下:

1<configuration>
2<appsettings>
3<add key="Copy" value="ABC公司"></add>
4<add key="Company" value="无锡市ABC信息技术有限公司"></add>
5<add key="ComUrl" value=" http://www.ABC.net.cn">
6</add></appsettings>
7</configuration>

读取我就不说了,很多人都会的!

引用:Imports System.Configuration名字空间

然后,

TBCopy.Text = ConfigurationSettings.AppSettings("Copy")
TBCompany.Text = ConfigurationSettings.AppSettings("Company")
TBComUrl.Text = ConfigurationSettings.AppSettings("ComUrl")

这样就调用了!

可是怎么样编辑呢?如何编辑它成了难题,首先在CSDN上找了很久,无果,到MSDN上也找了很久,不太适合,看来只有自己动手了! 因为其是个典型的XML文件,于是可以以XML的方法操作它!将下面的过程放到模块中或需要用到的地方!

Public Sub SysConfig(ByVal myValue() As String)
Dim i As Integer
Dim XmlDoc As New XmlDocument
XmlDoc.Load(Application.ExecutablePath & ".config")
Dim XN As XmlNode = XmlDoc.SelectSingleNode("/configuration/appSettings")
For i = 0 To myValue.Length - 1
XN.ChildNodes.Item(i).Attributes.ItemOf(1).Value() = myValue(i)
Next
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
XmlDoc = Nothing
End Sub

我是通过传递一个字符串数组来作参数的!每个值就是Config里的一行!按顺序排好!

Dim tmpStr() As String = {Trim(TBCopy.Text), Trim(TBCompany.Text), Trim(TBComUrl.Text)}
SysConfig(tmpStr)

这样就完成了修改的目的!

还有一种方法:

以Dataset方式读写Config及相关XML文件
Private Sub DealXML()
Dim myDs As New DataSet
myDs.ReadXml(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
TBCopy.Text = myDs.Tables(1).Rows(0)(1)
TBCompany.Text = myDs.Tables(1).Rows(1)(1)
TBComUrl.Text = myDs.Tables(1).Rows(2)(1)
'------------------------------------------
myDs.Tables(1).Rows(0)(1) = TBCopy.Text
myDs.Tables(1).Rows(1)(1) = TBCompany.Text
myDs.Tables(1).Rows(2)(1) = TBComUrl.Text
'------------------------------------------
myDs.AcceptChanges()
myDs.WriteXml(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)
myDs.Clear()
myDs.Dispose()
End Sub

至于喜欢用哪种都行!呵呵,完!有问题请联系我! [email protected]

Published At
Categories with Web编程
Tagged with
comments powered by Disqus