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.

Edited by Reverend Jim: Fixed code formatting

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
                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
        MsgBox("File does not exist")
    End If
5 Years
Discussion Span
Last Post by Nutster

You might want to change
Do While Not afile.EndOfData
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.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.