使用 TextFieldParser 对象分析文本文件

更新:2007 年 11 月

使用 TextFieldParser 对象可以分析和处理非常大的文件,这些文件的结构是以宽度分隔的文本列,如日志文件或旧版数据库信息。使用 TextFieldParser 分析文本文件与循环访问文本文件相似,而提取文本字段的分析方法则与将分隔字符串标记化所使用的字符串操作方法相似。

分析不同类型的文本文件

文本文件包含的字段可能有多种宽度,也可能使用字符(如逗号或制表符)分隔。如下例所示,定义 TextFieldType 和分隔符,该示例使用 SetDelimiters 方法定义制表符分隔的文本文件:

testReader.SetDelimiters(vbTab)

其他文本文件可能包含固定宽度的字段。在这种情况下,您需要将 TextFieldType 定义为 FixedWidth,并定义各字段的宽度,如下例所示。此示例使用 SetFieldWidths 方法定义文本列:第一列的宽度为 5 个字符,第二列的宽度为 10 个字符,第三列的宽度为 11 个字符,第四列的宽度是可变的。

testReader.SetFieldWidths(5, 10, 11, -1)
testReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth

定义了格式之后,您即可使用 ReadFields 方法依次处理各行来循环访问文件。

如果字段与指定的格式不匹配,将引发 MalformedLineException 异常。引发此类异常时,ErrorLine 和 ErrorLineNumber 属性将分别包含导致此异常的文本以及该文本所在的行号。

分析使用多种格式的文件

在读取各字段之前,可以使用 TextFieldParser 对象的 PeekChars 方法来检查字段,这样可以为字段定义多种格式并采取相应的操作。有关更多信息,请参见 如何:在 Visual Basic 中读取具有多种格式的文本文件

请参见

任务

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

参考

My.Computer.FileSystem.OpenTextFieldParser 方法

TextFieldParser 对象

TextFieldParser.PeekChars 方法

TextFieldParser.ReadFields 方法

TextFieldParser.CommentTokens 属性

TextFieldParser.Delimiters 属性

TextFieldParser.ErrorLine 属性

TextFieldParser.ErrorLineNumber 属性

TextFieldParser.FieldWidths 属性

TextFieldParser.HasFieldsEnclosedInQuotes 属性

TextFieldParser.LineNumber 属性

TextFieldParser.TextFieldType 属性

TextFieldParser.TrimWhiteSpace 属性

TextFieldParser.SetDelimiters 方法

TextFieldParser.SetFieldWidths 方法

修订记录

日期

修订

原因

2008 年 7 月

更新后的 SetFieldWidths 代码示例和注释。

客户反馈。