更新:2007 年 11 月
提供用于分析结构化文本文件的方法和属性。
Public Class TextFieldParser
异常
以下情况可能会导致异常:
- 文本字段与指定的格式不匹配。例如,在固定宽度的文件中,其中一个字段不符合指定的宽度。 (MalformedLineException).
备注
TextFieldParser 对象提供用于分析结构化文本文件的方法和属性。使用 TextFieldParser 分析文本文件与迭代文本文件相似,而用于提取文本中字段的 ReadFields 方法与拆分字符串相似。
TextFieldParser 可以分析两种类型的文件:符号分隔文件或固定宽度文件。有些属性,如 Delimiters 和 HasFieldsEnclosedInQuotes,仅在处理符号分隔文件时有意义,而 FieldWidths 属性仅在处理固定宽度文件时有意义。
任务
下表列出了涉及 Microsoft.VisualBasic.FileIO.TextFieldParser 对象的任务的示例。
| 要执行的操作 | 请参见 | 
|---|---|
| 从符号分隔的文本文件中读取 | |
| 从固定宽度的文本文件中读取 | |
| 从带有多种格式的文本文件中读取 | 
示例
本示例分析以制表符分隔的文本文件 Bigfile。
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser _
("c:\logs\bigfile")
    MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
    MyReader.Delimiters = New String() {vbTab}
    Dim currentRow As String()
    'Loop through all of the fields in the file. 
    'If any lines are corrupt, report an error and continue parsing. 
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.ReadFields()
            ' Include code here to handle the row.
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & _
            " is invalid.  Skipping")
        End Try
    End While
End Using
本示例依赖于 processFields 函数的存在,此函数在读取字段时对它们进行处理。
要求
命名空间:Microsoft.VisualBasic.FileIO
**程序集:**Visual Basic 运行库(在 Microsoft.VisualBasic.dll 中)
请参见
任务
关于异常的疑难解答:Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException
概念
参考
TextFieldParser.CommentTokens 属性
TextFieldParser.ErrorLineNumber 属性
TextFieldParser.FieldWidths 属性
TextFieldParser.HasFieldsEnclosedInQuotes 属性
TextFieldParser.TextFieldType 属性
TextFieldParser.TrimWhiteSpace 属性
TextFieldParser.SetDelimiters 方法
TextFieldParser.SetFieldWidths 方法