The TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs. The TextFieldType property defines whether it is a delimited file or one with fixed-width fields of text.
To parse a comma delimited text file
Create a new TextFieldParser. The following code creates the TextFieldParser named MyReader and opens the file test.txt.
Visual BasicUsing MyReader As New Microsoft.VisualBasic. FileIO.TextFieldParser( "C:\TestFolder\test.txt")
Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the delimiter as ",".
Visual BasicMyReader.TextFieldType = FileIO.FieldType.Delimited MyReader.SetDelimiters(",")Loop through the fields in the file. If any lines are corrupt, report an error and continue parsing. The following code loops through the file, displaying each field in turn and reporting any fields that are formatted incorrectly.
Visual BasicDim 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
Close the While and Using blocks with End While and End Using.
Visual BasicEnd While End Using
This example reads from the file 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
The following conditions may cause an exception:
-
A row cannot be parsed using the specified format (MalformedLineException). The exception message specifies the line causing the exception, while the ErrorLine property is assigned the text contained in the line.
-
The specified file does not exist (FileNotFoundException).
-
A partial-trust situation in which the user does not have sufficient permissions to access the file. (SecurityException).
-
The path is too long (PathTooLongException).
-
The user does not have sufficient permissions to access the file (UnauthorizedAccessException).