Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Visual Basic
 How to: Read From Comma-Delimited T...

  Switch on low bandwidth view
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
Visual Basic Application Development
How to: Read From Comma-Delimited 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 parse a comma delimited text file

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

    Visual Basic
    Using MyReader As New _
    Microsoft.VisualBasic.FileIO.TextFieldParser _
    ("C:\TestFolder\test.txt")
    
    
  2. Define the TextField type and delimiter. The following code defines the TextFieldType property as Delimited and the delimiter as ",".

    Visual Basic
    MyReader.TextFieldType = FileIO.FieldType.Delimited
    MyReader.SetDelimiters(",")
    
    
  3. 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 Basic
    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
    
    
  4. Close the While and Using blocks with End While and End Using.

    Visual Basic
       End While
    End Using
    
    

This example reads from the file test.txt.

Visual Basic
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.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:

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker