繁体   English   中英

使用Visual Basic读取INI文件

[英]Reading INI file with Visual Basic

我正在使用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,

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

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

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

任何帮助表示赞赏!

也许这不是最优雅的解决方案,但这是一个利用正则表达式解析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

用法示例

  • 一般读取值:

     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 
  • 将所有内容添加到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 

TreeView示例的屏幕截图

TreeView示例


正则表达式模式说明

  • SectionRegex

     \\[(?<section>[^\\n\\[\\]]+)\\]\\n*(?<valuelist>(.(?!\\[[^\\n\\[\\]]+\\]))*) \\[ => Match '['. (?<section> => Start of match group "section". [^ => Match any character... \\n\\[\\] => ...that is not '[', ']' or a new line... ]+ => ...and match this one or more times. ) => End of match group "section". \\] => Match ']'. \\n* => Match zero or more new lines (?<valuelist> => Start of match group "valuelist". ( => Start of unnamed match group. . => Match any character... (?! => ...that is not followed by... \\[[^\\n\\[\\]]+\\] => ...a section... ) )* => ...and match this zero or more times. ) => End of match group "valuelist". 
  • ValueRegex

     (?<valuename>[^=\\n]+)=(?<value>[^\\n]*) (?<valuename> => Start of match group "valuename". [^=\\n]+ => Match one or more characters that are not '=' or a new line. ) => End of match group "valuename". = => Match '='. (?<value> => Start of match group "value". [^\\n]* => Match zero or more characters that are not a new line. ) => End of match group "value". 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim a() As String = IO.File.ReadAllLines(iniPath)
    Dim user As String = "Jones"
    Dim data As String = "Project"

    For i = 0 To UBound(a)
        If a(i) = "[" + user + "]" Then
            For j = i To 1000
                If a(j).Contains(data) Then TextBox1.Text = a(j).Replace(data + "=", "") : Exit For
            Next
            Exit for
        End If
    Next
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM