Share via


How to: Read From Fixed-width Text Files in Visual Basic

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 specify a field of variable width in a fixed-width file, define the field width as -1.

To parse a fixed-width text file

  1. Create a new TextFieldParser. The following code creates the TextFieldParser named Reader and opens the file test.log.

    Using Reader As New _
    Microsoft.VisualBasic.FileIO.TextFieldParser _
    ("C:\TestFolder\test.log")
    
  2. Define the TextFieldType property as 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.

    Reader.TextFieldType = _
    Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
    Reader.SetFieldWidths(5, 10, 11, -1)
    
  3. 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
    
  4. Close the While and Using blocks with End While and End Using.

    End While 
    End Using
    

Example

This example reads from the file 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

Robust Programming

The following conditions may cause an exception:

See Also

Tasks

How to: Read From Comma-Delimited Text Files in Visual Basic

How to: Read From Text Files with Multiple Formats in Visual Basic

Walkthrough: Manipulating Files and Directories in Visual Basic

Troubleshooting: Reading from and Writing to Text Files

Troubleshooting Exceptions: Microsoft.VisualBasic.FileIO.TextFieldParser.MalformedLineException

Concepts

Parsing Text Files with the TextFieldParser Object

Reference

TextFieldParser Object