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

TextFieldParser 对象提供了一种轻松高效地分析结构化文本文件(如日志)的方法。

TextFieldType 属性定义分析的文件是带分隔符的文件还是具有固定宽度的文本字段的文件。 在固定宽度文本文件中,末尾的字段可以具有可变宽度。 若要指定末尾的字段具有可变宽度,请将其定义为宽度小于或等于零。

分析固定宽度的文本文件

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

    Using Reader As New Microsoft.VisualBasic.
        FileIO.TextFieldParser("C:\TestFolder\test.log")
    
  2. TextFieldType 属性定义为 FixedWidth,以指定宽度和格式。 以下代码定义文本列;第一个是宽 5 个字符,第二个 10 个字符,第三个 11 个字符,第四个字符是可变宽度。

    Reader.TextFieldType =
    Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    
  3. 遍历文件中的字段。 如果任何行已损坏,请报告错误并继续分析。

    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.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.log读取 。

Using Reader As New Microsoft.VisualBasic.FileIO.
   TextFieldParser("C:\TestFolder\test.log")

    Reader.TextFieldType =
       Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    Dim currentRow As String()
    While Not Reader.EndOfData
        Try
            currentRow = Reader.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

可靠编程

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

另请参阅