如何:在 Visual Basic 中从逗号分隔的文本文件中读取

TextFieldParser 对象提供了一种轻松高效地分析结构化文本文件(如日志)的方法。 该 TextFieldType 属性定义它是带分隔符的文件,还是具有固定宽度的文本字段。

分析逗号分隔的文本文件

  1. 新建 TextFieldParser。 以下代码创建 TextFieldParser 命名 MyReader 文件并打开该文件 test.txt

    Using MyReader As New Microsoft.VisualBasic.
                          FileIO.TextFieldParser(
                            "C:\TestFolder\test.txt")
    
  2. 定义TextField类型和分隔符。 以下代码将 TextFieldType 属性 Delimited 定义为“,”分隔符。

    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    
  3. 遍历文件中的字段。 如果任何行已损坏,请报告错误并继续分析。 以下代码遍历文件,依次显示每个字段,并报告格式不正确的字段。

    
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.ReadFields()
            Dim currentField As String
            For Each currentField In currentRow
                MsgBox(currentField)
            Next
        Catch ex As Microsoft.VisualBasic.
                    FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    
  4. 使用WhileUsing关闭End WhileEnd Using块。

        End While
    End Using
    

示例:

此示例从文件 test.txt读取 。

Using MyReader As New Microsoft.VisualBasic.
                      FileIO.TextFieldParser(
                        "C:\TestFolder\test.txt")
    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.ReadFields()
            Dim currentField As String
            For Each currentField In currentRow
                MsgBox(currentField)
            Next
        Catch ex As Microsoft.VisualBasic.
                    FileIO.MalformedLineException
            MsgBox("Line " & ex.Message &
            "is not valid and will be skipped.")
        End Try
    End While
End Using

可靠编程

以下条件可能会导致异常:

另请参阅