How to: Read From Fixed-width Text Files in Visual Basic
Updated: July 20, 2015
For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.
TextFieldParser object provides a way to easily and efficiently parse structured text files, such as logs.
TextFieldType property defines whether the parsed file is a delimited file or one that has fixed-width fields of text. In a fixed-width text file, the field at the end can have a variable width. To specify that the field at the end has a variable width, define it to have a width less than or equal to zero.
Create a new
TextFieldParser. The following code creates the
Readerand opens the file
FixedWidth, defining the width and format. The following code defines the columns of text; the first is 5 characters wide, the second 10, the third 11, and the fourth is of variable width.
Loop through the fields in the file. If any lines are corrupted, report an error and continue parsing.
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
This example reads from the file
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
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 to 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).
How to: Read From Comma-Delimited Text Files
How to: Read From Text Files with Multiple Formats
Parsing Text Files with the TextFieldParser Object
Walkthrough: Manipulating Files and Directories in Visual Basic
Troubleshooting: Reading from and Writing to Text Files
Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException