如何:在 Visual Basic 中读取具有多种格式的文本文件
更新:2007 年 11 月
TextFieldParser 对象提供了一种可以轻松而高效地分析结构化文本文件(如日志)的方法。分析整个文件时,可以通过使用 PeekChars 方法来确定各行的格式,从而处理具有多种格式的文件。
分析具有多种格式的文本文件
定义预期格式以及在报告错误时使用的格式。
Dim StdFormat As Integer()= {5,10,11,-1} Dim ErrorFormat As Integer() = {5,5,-1}
创建一个新的 TextFieldParser 对象,用于定义宽度和格式。
Using MyReader As New _ Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt") MyReader.TextFieldType = FileIO.FieldType.FixedWidth
依次通过各行,并在读取之前测试格式。
Dim CurrentRow As String() While Not MyReader.EndOfData Try Dim RowType As String = MyReader.PeekChars(3) If String.Compare(RowType, "Err") = 0 Then ' If this line describes an error, the format of ' the row will be different. MyReader.SetFieldWidths(ErrorFormat) CurrentRow = MyReader.ReadFields MyReader.SetFieldWidths(StdFormat) Else 'Otherwise parse the fields normally CurrentRow = MyReader.ReadFields For Each newString As String In CurrentRow My.Computer.FileSystem.WriteAllText _ ("newFile.txt", newString, True) Next End If
将错误写入控制台。
Catch ex As _ Microsoft.VisualBasic.FileIO.MalformedLineException MsgBox("Line " & ex.Message & " is invalid.") End Try End While End Using
示例
此示例读取文件 testfile.txt。
Dim StdFormat As Integer() = {5, 10, 11, -1}
Dim ErrorFormat As Integer() = {5, 5, -1}
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.FixedWidth
MyReader.FieldWidths = StdFormat
Dim CurrentRow As String()
While Not MyReader.EndOfData
Try
Dim RowType As String = MyReader.PeekChars(3)
If String.Compare(RowType, "Err") = 0 Then
' If this line describes an error, the format of the row will be different.
MyReader.SetFieldWidths(ErrorFormat)
CurrentRow = MyReader.ReadFields
MyReader.SetFieldWidths(StdFormat)
Else
' Otherwise parse the fields normally
CurrentRow = MyReader.ReadFields
For Each newString As String In CurrentRow
My.Computer.FileSystem.WriteAllText("newFile.txt", newString, True)
Next
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is invalid. Skipping")
End Try
End While
End Using
可靠编程
以下情况可能会导致异常:
无法使用指定的格式分析行 (MalformedLineException)。此异常消息指定导致发生异常的行,而 TextFieldParser.ErrorLine 属性分配给该行中包含的文本。
指定的文件不存在 (FileNotFoundException)。
部分信任的情况,在这种情况下,用户没有访问文件的足够权限。 (SecurityException).
路径太长 (PathTooLongException)。
用户没有足够的权限访问文件 (UnauthorizedAccessException)。
请参见
任务
如何:在 Visual Basic 中读取逗号分隔的文本文件
如何:在 Visual Basic 中读取固定宽度的文本文件