使用Visual Basic读取INI文件

Al *_* F. 1 vb.net ini

我正在使用Visual Basic读取包含经常使用的信息的文件。具体来说,我的文件包含以下信息:

[Smith]
Name=Sam Smith
Email=sam.smith@yahoo.com
Project=Smith's Treehouse Project
Greeting=Hi Sam,

[Jones]
Name=Josh Jones
Email=josh.jones@gmail.com
Project=Jone's Second-Story Remodel
Greeting=Hi Josh,
Run Code Online (Sandbox Code Playgroud)

然后,我试图将信息读入一个简单的VB命令(实际上使用Dragon Naturally Speaking,但这没关系)在Microsoft Outlook中发送电子邮件。我不需要写入文件或更改值。我只需要阅读信息,因此可以使用列表变量将电子邮件地址发送到地址字段,将项目名称发送到主题字段,等等。

如何编写从文件读取的功能?

我花了大约4个小时在这里和其他网站上寻找答案,但感到困惑。(我显然是VB的新手。)似乎每次我找到看起来很接近的代码时,它都使用独特的编码功能,所以我不知道正确的代码是什么。

任何帮助表示赞赏!

Vis*_*ent 6

也许这不是最优雅的解决方案,但这是一个使用正则表达式解析INI的类:

Imports System.IO
Imports System.Text.RegularExpressions

Public NotInheritable Class IniParser
    Private Shared SectionRegex As New Regex("\[(?<section>[^\n\[\]]+)\]\n*(?<valuelist>(.(?!\[[^\n\[\]]+\]))*)", RegexOptions.Singleline Or RegexOptions.CultureInvariant Or RegexOptions.Compiled)
    Private Shared ValueRegex As New Regex("(?<valuename>[^=\n]+)=(?<value>[^\n]*)", RegexOptions.CultureInvariant Or RegexOptions.Compiled)

    ''' <summary>
    ''' Parses an .ini-file.
    ''' </summary>
    ''' <param name="FileName">The path to the file to parse.</param>
    ''' <remarks></remarks>
    Public Shared Function ParseFile(ByVal FileName As String) As Dictionary(Of String, Dictionary(Of String, String))
        Return IniParser.Parse(File.ReadAllText(FileName))
    End Function

    ''' <summary>
    ''' Parses a text of .ini-format.
    ''' </summary>
    ''' <param name="Data">The text to parse.</param>
    ''' <remarks></remarks>
    Public Shared Function Parse(ByVal Data As String) As Dictionary(Of String, Dictionary(Of String, String))
        Dim Result As New Dictionary(Of String, Dictionary(Of String, String)) '(Section, (Value name, Value))
        Dim Sections As MatchCollection = SectionRegex.Matches(Data)

        'Iterate each section.
        For Each SectionMatch As Match In Sections
            Dim Section As New Dictionary(Of String, String)
            Dim SectionName As String = SectionMatch.Groups("section").Value
            Dim Values As MatchCollection = ValueRegex.Matches(SectionMatch.Groups("valuelist").Value)

            If Result.ContainsKey(SectionName) = True Then
                'A section by this name already exists.
                Dim i As Integer = 1

                'Append a number to the section name until a unique name is found.
                While Result.ContainsKey(SectionName & i)
                    i += 1
                End While

                Result.Add(SectionName & i, Section)
            Else
                'A section by this name does not exist.
                Result.Add(SectionName, Section)
            End If

            'Iterate each value of this section.
            For Each ValueMatch As Match In Values
                Dim ValueName As String = ValueMatch.Groups("valuename").Value
                Dim Value As String = ValueMatch.Groups("value").Value

                If Section.ContainsKey(ValueName) = True Then
                    'A value by this name already exists.
                    Dim i As Integer = 1

                    'Append a number to the value name until a unique name is found.
                    While Section.ContainsKey(ValueName & i)
                        i += 1
                    End While

                    Section.Add(ValueName & i, Value)
                Else
                    'A value by this name does not exist.
                    Section.Add(ValueName, Value)
                End If
            Next
        Next

        Return Result
    End Function
End Class
Run Code Online (Sandbox Code Playgroud)

用法示例

  • 一般读取值:

    Dim IniContents As Dictionary(Of String, Dictionary(Of String, String)) = IniParser.ParseFile("C:\path\to\your\file\here.ini")
    
    For Each SectionName As String In IniContents.Keys
        For Each ValueName As String In IniContents(SectionName).Keys
            Dim Value As String = IniContents(SectionName)(ValueName)
    
            '[SectionName]
            'ValueName=Value
            'ValueName=Value
            '
            'SectionName: The name of the current section (ex: Jones).
            'ValueName  : The name of the current value   (ex: Email).
            'Value      : The value of [ValueName]        (ex: josh.jones@gmail.com).
            Console.WriteLine(SectionName & ": " & ValueName & " = " & Value)
        Next
    Next
    
    Run Code Online (Sandbox Code Playgroud)
  • 将所有内容添加到TreeView,其中节点的Tag属性为值:

    Dim IniContents As Dictionary(Of String, Dictionary(Of String, String)) = IniParser.ParseFile("C:\path\to\your\file\here.ini")
    
    For Each SectionName As String In IniContents.Keys
        Dim TopNode As TreeNode = TreeView1.Nodes.Add(SectionName)
        Dim Section As Dictionary(Of String, String) = IniContents(SectionName)
    
        For Each ValueName As String In Section.Keys
            TopNode.Nodes.Add(New TreeNode(ValueName) With {.Tag = Section(ValueName)})
        Next
    Next
    
    Run Code Online (Sandbox Code Playgroud)

TreeView示例的屏幕截图

TreeView示例


正则表达式模式说明

  • SectionRegex

    Imports System.IO
    Imports System.Text.RegularExpressions
    
    Public NotInheritable Class IniParser
        Private Shared SectionRegex As New Regex("\[(?<section>[^\n\[\]]+)\]\n*(?<valuelist>(.(?!\[[^\n\[\]]+\]))*)", RegexOptions.Singleline Or RegexOptions.CultureInvariant Or RegexOptions.Compiled)
        Private Shared ValueRegex As New Regex("(?<valuename>[^=\n]+)=(?<value>[^\n]*)", RegexOptions.CultureInvariant Or RegexOptions.Compiled)
    
        ''' <summary>
        ''' Parses an .ini-file.
        ''' </summary>
        ''' <param name="FileName">The path to the file to parse.</param>
        ''' <remarks></remarks>
        Public Shared Function ParseFile(ByVal FileName As String) As Dictionary(Of String, Dictionary(Of String, String))
            Return IniParser.Parse(File.ReadAllText(FileName))
        End Function
    
        ''' <summary>
        ''' Parses a text of .ini-format.
        ''' </summary>
        ''' <param name="Data">The text to parse.</param>
        ''' <remarks></remarks>
        Public Shared Function Parse(ByVal Data As String) As Dictionary(Of String, Dictionary(Of String, String))
            Dim Result As New Dictionary(Of String, Dictionary(Of String, String)) '(Section, (Value name, Value))
            Dim Sections As MatchCollection = SectionRegex.Matches(Data)
    
            'Iterate each section.
            For Each SectionMatch As Match In Sections
                Dim Section As New Dictionary(Of String, String)
                Dim SectionName As String = SectionMatch.Groups("section").Value
                Dim Values As MatchCollection = ValueRegex.Matches(SectionMatch.Groups("valuelist").Value)
    
                If Result.ContainsKey(SectionName) = True Then
                    'A section by this name already exists.
                    Dim i As Integer = 1
    
                    'Append a number to the section name until a unique name is found.
                    While Result.ContainsKey(SectionName & i)
                        i += 1
                    End While
    
                    Result.Add(SectionName & i, Section)
                Else
                    'A section by this name does not exist.
                    Result.Add(SectionName, Section)
                End If
    
                'Iterate each value of this section.
                For Each ValueMatch As Match In Values
                    Dim ValueName As String = ValueMatch.Groups("valuename").Value
                    Dim Value As String = ValueMatch.Groups("value").Value
    
                    If Section.ContainsKey(ValueName) = True Then
                        'A value by this name already exists.
                        Dim i As Integer = 1
    
                        'Append a number to the value name until a unique name is found.
                        While Section.ContainsKey(ValueName & i)
                            i += 1
                        End While
    
                        Section.Add(ValueName & i, Value)
                    Else
                        'A value by this name does not exist.
                        Section.Add(ValueName, Value)
                    End If
                Next
            Next
    
            Return Result
        End Function
    End Class
    
    Run Code Online (Sandbox Code Playgroud)
  • ValueRegex

    Dim IniContents As Dictionary(Of String, Dictionary(Of String, String)) = IniParser.ParseFile("C:\path\to\your\file\here.ini")
    
    For Each SectionName As String In IniContents.Keys
        For Each ValueName As String In IniContents(SectionName).Keys
            Dim Value As String = IniContents(SectionName)(ValueName)
    
            '[SectionName]
            'ValueName=Value
            'ValueName=Value
            '
            'SectionName: The name of the current section (ex: Jones).
            'ValueName  : The name of the current value   (ex: Email).
            'Value      : The value of [ValueName]        (ex: josh.jones@gmail.com).
            Console.WriteLine(SectionName & ": " & ValueName & " = " & Value)
        Next
    Next
    
    Run Code Online (Sandbox Code Playgroud)