Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports System.IO
- Imports System.Text.RegularExpressions
- Public Class IniFile : Inherits Dictionary(Of String, IniGroup)
- Public Sub New()
- MyBase.New()
- End Sub
- Public Shared Function Parse(ByVal ini As String) As IniFile
- If IO.File.Exists(ini) Then
- Dim file As New IniFile()
- Dim curGroup As String = String.Empty
- Using sReader As New IO.StreamReader(ini)
- Dim line As String = String.Empty
- While Not sReader.EndOfStream
- line = sReader.ReadLine()
- Dim m As Match = Regex.Match(line, "^\s*\[(?<group>[^\]]*)]\s*$", RegexOptions.Compiled)
- If m.Success AndAlso m.Groups("group") IsNot Nothing AndAlso Not String.IsNullOrEmpty(m.Groups("group").Value) Then
- Dim group As String = m.Groups("group").Value
- If Not file.ContainsKey(group) Then file.Add(group, New IniGroup(group))
- curGroup = group
- ElseIf Not String.IsNullOrEmpty(curGroup) Then
- file(curGroup).AddProperty(line)
- End If
- End While
- End Using
- Return file
- Else
- Return Nothing
- End If
- End Function
- Public Shared Function Write(ByVal ini As IniFile, ByVal filepath As String) As Boolean
- If ini IsNot Nothing Then
- Try
- IO.File.WriteAllText(filepath, String.Join(Environment.NewLine, ini.Values.Select(Function(g As IniGroup) g.ToString()).ToArray()))
- Return True
- Catch ex As Exception
- Return False
- End Try
- Else
- Return False
- End If
- End Function
- End Class
- Public Class IniGroup : Inherits Dictionary(Of String, String)
- Public Property Name As String
- Public Sub New(ByVal name As String)
- MyBase.New()
- Me.Name = name
- End Sub
- Public Function AddProperty(ByVal propertyLine As String) As Boolean
- If Not String.IsNullOrEmpty(propertyLine) AndAlso propertyLine.Contains("=") Then
- Dim sections As String() = propertyLine.Split("="c)
- If sections.Length = 2 Then
- sections(0) = sections(0).Trim()
- sections(1) = sections(1).Trim()
- If Not Me.ContainsKey(sections(0)) Then
- Me.Add(sections(0), sections(1))
- Else
- Me(sections(0)) = sections(1)
- End If
- Return True
- End If
- End If
- Return False
- End Function
- Public Overrides Function ToString() As String
- Dim sBuilder As New System.Text.StringBuilder()
- sBuilder.AppendLine(String.Format("[{0}]", Me.Name))
- For Each kvp As KeyValuePair(Of String, String) In Me
- sBuilder.AppendLine(String.Format("{0} = {1}", kvp.Key, kvp.Value))
- Next
- Return sBuilder.ToString()
- End Function
- End Class
Add Comment
Please, Sign In to add comment