(声明:魏滔序原创,转贴请注明出处。)
在早期的vb6编程时,习惯把配置信息保存在ini、xml或注册表中,到.net里面就方便多了,ms他老人家细心的加入了这个功能,感谢啊,方便程度不一般。下面是读写Config的类,示例程序就不用写了吧。
Imports System
Imports System.Xml
Imports System.Configuration
Imports System.Collections
Imports System.Reflection
Imports System.Diagnostics
Public Enum ConfigFileType
WebConfig
AppConfig
End Enum
Public Class Config
Inherits System.Configuration.AppSettingsReader
Public docName As String = String.Empty
Private node As XmlNode = Nothing
Private _configType As ConfigFileType = ConfigFileType.AppConfig
Public Property ConfigType() As ConfigFileType
Get
Return _configType
End Get
Set(ByVal value As ConfigFileType)
_configType = value
End Set
End Property
Public Function GetConfigValue(ByVal Key As String, ByVal Type As System.Type) As Object
Dim configurationAppSettings As System.Configuration.AppSettingsReader = New System.Configuration.AppSettingsReader
Return configurationAppSettings.GetValue(Key, Type)
End Function
Public Function GetConfigValue(ByVal Key As String) As Object
Dim configurationAppSettings As New System.Configuration.AppSettingsReader
Return configurationAppSettings.GetValue(Key, GetType(String))
End Function
Public Function SetConfigValue(ByVal key As String, ByVal value As String) As Boolean
Dim cfgDoc As XmlDocument = New XmlDocument
loadConfigDoc(cfgDoc)
node = cfgDoc.SelectSingleNode("//appSettings")
If node Is Nothing Then
Throw New System.InvalidOperationException("appSettings section not found")
End If
Try
Dim addElem As XmlElement = CType(node.SelectSingleNode("//add[@key='" + key + "']"), XmlElement)
If Not (addElem Is Nothing) Then
addElem.SetAttribute("value", value)
Else
Dim entry As XmlElement = cfgDoc.CreateElement("add")
entry.SetAttribute("key", key)
entry.SetAttribute("value", value)
node.AppendChild(entry)
End If
saveConfigDoc(cfgDoc, docName)
Return True
Catch
Return False
End Try
End Function
Private Sub saveConfigDoc(ByVal cfgDoc As XmlDocument, ByVal cfgDocPath As String)
Try
Dim writer As XmlTextWriter = New XmlTextWriter(cfgDocPath, Nothing)
writer.Formatting = Formatting.Indented
cfgDoc.WriteTo(writer)
writer.Flush()
writer.Close()
Return
Catch
Throw
End Try
End Sub
Public Function removeElement(ByVal elementKey As String) As Boolean
Try
Dim cfgDoc As XmlDocument = New XmlDocument
loadConfigDoc(cfgDoc)
node = cfgDoc.SelectSingleNode("//appSettings")
If node Is Nothing Then
Throw New System.InvalidOperationException("appSettings section not found")
End If
node.RemoveChild(node.SelectSingleNode("//add[@key='" + elementKey + "']"))
saveConfigDoc(cfgDoc, docName)
Return True
Catch
Return False
End Try
End Function
Private Function loadConfigDoc(ByVal cfgDoc As XmlDocument) As XmlDocument
If Convert.ToInt32(ConfigType) = Convert.ToInt32(ConfigFileType.AppConfig) Then
docName = ((Assembly.GetEntryAssembly).GetName).Name
docName += ".exe.config"
Else
docName = System.Web.HttpContext.Current.Server.MapPath("web.config")
End If
cfgDoc.Load(docName)
Return cfgDoc
End Function
End Class