TextFieldParser 对象提供了一种可以轻松而高效地分析结构化文本文件(如日志)的方法。 TextFieldType 属性用于定义文件是符号分隔的还是具有固定宽度文本字段的。
分析逗号分隔的文本文件
- 创建一个新的 TextFieldParser。 下面的代码创建名为 MyReader 的 TextFieldParser,并打开 test.txt 文件。 - Using MyReader As New Microsoft.VisualBasic. FileIO.TextFieldParser( "C:\TestFolder\test.txt")
- 定义 TextField 类型和分隔符。 下面的代码将 TextFieldType 属性定义为 Delimited,并将分隔符定义为“,”。 - 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 结束 While 和 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
可靠编程
以下情况可能会导致异常:
- 无法使用指定的格式分析某行 (MalformedLineException)。 此异常消息指定导致发生异常的行,同时为 ErrorLine 属性分配该行中包含的文本。 
- 指定的文件不存在 (FileNotFoundException)。 
- 在部分信任的情况下,用户没有访问文件的足够权限。 (SecurityException). 
- 路径太长 (PathTooLongException)。 
- 用户没有足够的权限访问文件 (UnauthorizedAccessException)。 
请参见
任务
如何:在 Visual Basic 中读取固定宽度的文本文件
如何:在 Visual Basic 中读取具有多种格式的文本文件
关于异常的疑难解答:Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
参考
Microsoft.VisualBasic.FileIO.TextFieldParser