Read in text from CSV with TextFieldParser

Updated G_Waddell 1 Tallied Votes 5K Views Share

Hi All,
In my opinion, this is the best way to read in text from a csv file.

Take for example if you are importing addresses:

"1 Main Street","SmallTown","SmallCounty"

The above is fine and easy to parse in BUT what if an address like this was entered:

"App 1A, Tall Towers","SmallTown","SmallCounty"

By setting the parser setting delimiter to the comma AND also marking that the fields are enclosed in quotes, the parser knows the comma in the middle of the quotes is not a delimiter and therefore brings the text in as one field.

Imports Microsoft.VisualBasic.FileIO.TextFieldParser
Imports System.IO

Sub ParseCSVFile(byref Filename as String)

    If File.Exists(Filename) Then
    
        Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(FileName)
        Dim CurrentRecord As String() ' this array will hold each line of data
        'Tell the parser we are using delimited text file
        afile.TextFieldType = FileIO.FieldType.Delimited
        'Tell Parser how we will delimit
        afile.Delimiters = New String() {","}
        'For this example field will be enclosed in quotes i.e. "MyEntry","MyEntry2"
        afile.HasFieldsEnclosedInQuotes = True
        
        Do While Not afile.EndOfData
            try
                CurrentRecord = afile.ReadFields
                'Now we have our line in an array CurrentRecord 
                'Do what we wish with it
            catch ex As FileIO.MalformedLineException
                msgbox("Malformed Text")
                Exit Loop
            end try
        Loop
    
    Else
        MsgBox("File does not exist")
    End If
Begginnerdev 256 Junior Poster

Nice code snippet! Thanks, George!

Nutster 58 Newbie Poster

You might want to change
Do While Not afile.EndOfData
to
Do Until afile.EndOfData

One less operation, making it easier to read and maintain, and maybe a little faster.

Also, in your Catch block, I would use Continue Do instead of Exit Do. Just because one line is messed up does not mean the ones following it are. Continue would go back to the top of the loop and try to read the next line, rather than giving up on the first bad line.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.