如何:在 Visual Basic 中读取具有多种格式的文本文件

TextFieldParser 对象提供了一种可以轻松而高效地分析结构化文本文件(如日志)的方法。 分析整个文件时,可以通过使用 PeekChars 方法来确定各行的格式,从而处理具有多种格式的文件。

分析具有多种格式的文本文件

  1. 将名为 testfile.txt 的文本文件添加到您的项目。 向文本文件中添加以下内容。

    Err  1001 Cannot access resource.
    Err  2014 Resource not found.
    Acc  10/03/2009User1      Administrator.
    Err  0323 Warning: Invalid access attempt.
    Acc  10/03/2009User2      Standard user.
    Acc  10/04/2009User2      Standard user.
    
  2. 定义预期格式以及在报告错误时使用的格式。 每个数组中的最后一项为 -1,因此假定最后一个字段具有可变宽度。 如果数组中的最后一项小于或等于 0,则会出现这种情况。

    Dim stdFormat As Integer() = {5, 10, 11, -1}
    Dim errorFormat As Integer() = {5, 5, -1}
    
  3. 创建一个新的 TextFieldParser 对象,用于定义宽度和格式。

    Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
        MyReader.TextFieldType = FileIO.FieldType.FixedWidth
        MyReader.FieldWidths = stdFormat
    
  4. 依次通过各行,并在读取之前测试格式。

    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            Dim rowType = MyReader.PeekChars(3)
            If String.Compare(rowType, "Err") = 0 Then
                ' If this line describes an error, the format of the row will be different.
                MyReader.SetFieldWidths(errorFormat)
            Else
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
    
  5. 将错误写入控制台。

          Catch ex As Microsoft.VisualBasic.
                        FileIO.MalformedLineException
             MsgBox("Line " & ex.Message & " is invalid.")
          End Try
       End While
    End Using
    

示例

下面是一个摘自 testfile.txt 文件的完整示例。

Dim stdFormat As Integer() = {5, 10, 11, -1}
Dim errorFormat As Integer() = {5, 5, -1}
Using MyReader As New FileIO.TextFieldParser("..\..\testfile.txt")
    MyReader.TextFieldType = FileIO.FieldType.FixedWidth
    MyReader.FieldWidths = stdFormat
    Dim currentRow As String()
    While Not MyReader.EndOfData
        Try
            Dim rowType = MyReader.PeekChars(3)
            If String.Compare(rowType, "Err") = 0 Then
                ' If this line describes an error, the format of the row will be different.
                MyReader.SetFieldWidths(errorFormat)
            Else
                ' Otherwise parse the fields normally
                MyReader.SetFieldWidths(stdFormat)
            End If
            currentRow = MyReader.ReadFields
            For Each newString In currentRow
                Console.Write(newString & "|")
            Next
            Console.WriteLine()
        Catch ex As FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & " is invalid.  Skipping")
        End Try
    End While
End Using
Console.ReadLine()

可靠编程

以下情况可能会导致异常:

请参见

任务

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

如何:在 Visual Basic 中读取固定宽度的文本文件

参考

Microsoft.VisualBasic.FileIO.TextFieldParser

PeekChars

MalformedLineException

WriteAllText

EndOfData

TextFieldType

概念

使用 TextFieldParser 对象分析文本文件 (Visual Basic)