TextFieldParser 对象提供了一种可以轻松而高效地分析结构化文本文件(如日志)的方法。
TextFieldType 属性用于定义分析文件是分隔文件还是具有固定宽度文本字段的文件。 在固定宽度的文本文件中,末尾字段的宽度可变。 若要指定末尾字段具有可变宽度,可将该字段的宽度定义为小于或等于零。
分析固定宽度的文本文件
- 创建一个新的 TextFieldParser。 下面的代码创建名为 Reader 的 TextFieldParser,并打开 test.log 文件。 - Using Reader As New Microsoft.VisualBasic. FileIO.TextFieldParser("C:\TestFolder\test.log")
- 将 TextFieldType 属性定义为 FixedWidth,并定义宽度和格式。 下面的代码定义文本列;第一列的宽度为 5 个字符,第二列的宽度为 10 个字符,第三列的宽度为 11 个字符,第四列的宽度是可变的。 - 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 关闭 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
可靠编程
以下情况可能会导致异常:
- 无法使用指定的格式分析某行 (MalformedLineException)。 此异常消息指定导致发生异常的行,而 ErrorLine 属性分配给该行中包含的文本。 
- 指定的文件不存在 (FileNotFoundException)。 
- 在部分信任的情况下,用户没有访问文件的足够权限。 (SecurityException). 
- 路径太长 (PathTooLongException)。 
- 用户没有足够的权限访问文件 (UnauthorizedAccessException)。 
请参见
任务
如何:在 Visual Basic 中读取逗号分隔的文本文件
如何:在 Visual Basic 中读取具有多种格式的文本文件
关于异常的疑难解答:Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
参考
Microsoft.VisualBasic.FileIO.TextFieldParser
概念
使用 TextFieldParser 对象分析文本文件 (Visual Basic)
修订记录
| 日期 | 修订记录 | 原因 | 
| 2011 年 1 月 | 添加了有关可变宽度字段的信息。 | 客户反馈 |