没有使用windows自带的api。
源代码:
Imports System.IO
Public Class ConfigEditor
Dim m_ConfigName As String
Dim Lines() As String
Sub New(ByVal ConfigFileName As String)
m_ConfigName = ConfigFileName
End Sub
Sub Load()
Using Rd As New StreamReader(m_ConfigName)
Lines = Split(Rd.ReadToEnd, vbCrLf)
End Using
End Sub
Sub Save()
Using Wt As New StreamWriter(m_ConfigName)
For i = 0 To Lines.GetUpperBound(0)
If Lines(i) <> "" Then
Wt.WriteLine(Lines(i))
End If
Next
Wt.Flush()
End Using
End Sub
Public Property Key(ByVal Domain As String, ByVal Item As String) As String
Get
Load()
Dim IsItem As Boolean = False
For i = 0 To Lines.GetUpperBound(0)
If Lines(i) = "[" & Domain & "]" Then
IsItem = True
ElseIf IsItem AndAlso InStr(Lines(i), "[") > 0 AndAlso InStr(Lines(i), "]") > InStr(Lines(i), "[") Then
Return ""
End If
Dim Value = Split(Lines(i), "=")
If IsItem AndAlso Value.First = Item AndAlso Value.GetUpperBound(0) >= 1 Then
Return Value(1)
End If
Next
Return ""
End Get
Set(ByVal value As String)
Load()
If Not DomainExists(Domain) Then
ReDim Preserve Lines(Lines.GetUpperBound(0) + 1)
Lines(Lines.GetUpperBound(0)) = "[" & Domain & "]"
Save()
Load()
End If
If Not ItemExists(Domain, Item) Then
For i = 0 To Lines.GetUpperBound(0)
If Lines(i) = "[" & Domain & "]" Then
Lines(i) &= vbCrLf & Item & "="
Exit For
End If
Next
Save()
Load()
End If
Dim IsItem As Boolean = False
For i = 0 To Lines.GetUpperBound(0)
If Lines(i) = "[" & Domain & "]" Then
IsItem = True
End If
If IsItem AndAlso Split(Lines(i), "=").First = Item Then
Lines(i) = Item & "=" & value
Exit For
End If
Next
Save()
End Set
End Property
Function DomainExists(ByVal Domain As String) As Boolean
Load()
For i = 0 To Lines.GetUpperBound(0)
If Lines(i) = "[" & Domain & "]" Then
Return True
End If
Next
Return False
End Function
Function ItemExists(ByVal Domain As String, ByVal Item As String) As Boolean
Load()
Dim IsItem As Boolean = False
For i = 0 To Lines.GetUpperBound(0)
If Lines(i) = "[" & Domain & "]" Then
IsItem = True
ElseIf IsItem AndAlso InStr(Lines(i), "[") > 0 AndAlso InStr(Lines(i), "]") > InStr(Lines(i), "[") Then
Return False
End If
Dim Value = Split(Lines(i), "=")
If IsItem AndAlso Value.First = Item AndAlso Value.GetUpperBound(0) >= 1 Then
Return True
End If
Next
Return False
End Function
End Class
代码丑陋, 请见谅
使用方法:
发表评论