该 TextFieldParser
对象提供了一种轻松高效地分析结构化文本文件(如日志)的方法。
该 TextFieldType
属性定义分析的文件是带分隔符的文件还是具有固定宽度的文本字段的文件。 在固定宽度文本文件中,末尾的字段可以具有可变宽度。 若要指定末尾的字段具有可变宽度,请将其定义为宽度小于或等于零。
分析固定宽度的文本文件
新建
TextFieldParser
。 以下代码创建TextFieldParser
命名Reader
文件并打开该文件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
使用
While
和Using
关闭End While
和End 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)。