该 TextFieldParser
对象提供了一种轻松高效地分析结构化文本文件(如日志)的方法。 该 TextFieldType
属性定义它是带分隔符的文件,还是具有固定宽度的文本字段。
分析逗号分隔的文本文件
新建
TextFieldParser
。 以下代码创建TextFieldParser
命名MyReader
文件并打开该文件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
使用
While
和Using
关闭End While
和End 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)。