rusty "Razorblade" coslett
stainless musings

CSV Parsing No More: TextFieldParser

Wednesday, April 22, 2009 2:53 PM
Searched all over the net to NOT have to write another CSV Parser.  I want to just say 'go do it now, no complaining just go'.  I was happy to have found somewhere along my search the Microsoft.VisualBasic.FileIO.TextFieldParser.

Works great for what I needed with no worries about line length, terminators, etc.  I also did not have embedded commas in my file.

Adios!

   Private Sub walkTheCSV(ByVal fileName As String)

 

        If (String.IsNullOrEmpty(fileName)) Then

            Return

        End If

 

        ' check if it exists, etc.

 

        Using tp As New TextFieldParser(fileName)

 

            tp.TextFieldType = FileIO.FieldType.Delimited

            tp.SetDelimiters(",")

 

            Dim currentRow As String()

            While Not tp.EndOfData

 

                Try

                    currentRow = tp.ReadFields()

 

                    For Each currentField As String In currentRow

 

                        If (String.IsNullOrEmpty(currentField)) Then

                            Continue For ' do not care to process an empty field

                        End If

 

                    Next

 

                Catch ex As MalformedLineException

                    ' eat it or move on...

                End Try

 

            End While

 

        End Using

 

    End Sub

 


Feedback

# re: CSV Parsing No More: TextFieldParser

Thanks for posting this! 4/22/2009 5:10 PM | Josh

# re: CSV Parsing No More: TextFieldParser

Hope it helped, I am tired of writing so much plumbing code.

rusty 4/27/2009 1:31 PM | rusty

Post a comment