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

更新:2007 年 11 月

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

TextFieldType 属性定义文件是符号分隔的文件还是具有固定宽度文本字段的文件。若要指定固定宽度文件中宽度可变的字段,请将字段宽度定义为 -1。

分析固定宽度的文本文件

  1. 创建一个新的 TextFieldParser。下面的代码创建名为 Reader 的 TextFieldParser,并打开文件 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. 使用 End While 和 End Using 关闭 While 和 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

可靠编程

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

请参见

任务

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

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

演练:在 Visual Basic 中操作文件和目录

疑难解答:读取和写入文本文件

关于异常的疑难解答:Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException

概念

使用 TextFieldParser 对象分析文本文件

参考

TextFieldParser 对象