Search code examples
vb.netparsingcsvstreamreaderdatareader

Malformed CSV at end


Hey all i am trying to figure out a way of correcting the error in my CSV file before it errors out with a MalformedLineException.

My code is this:

Using myreader As New Microsoft.VisualBasic.FileIO.TextFieldParser("c:\temp.csv")
        myreader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
        myreader.Delimiters = New String() {",", "\n"}
        myreader.HasFieldsEnclosedInQuotes = True 'Added

        While Not myreader.EndOfData
            Try
                currentrow = myreader.ReadFields()

The error is on the currentrow = myreader.ReadFields(). It's caused by not having the end quote in the last line of the CSV:

"xx.xxx.xxx.xx","2012-05-15 13:15:54","Bob Barker","bbarker@priceisright.com","

It should read:

"xx.xxx.xxx.xx","2012-05-15 13:15:54","Bob Barker","bbarker@priceisright.com",""

How can i correct this before it gets to the line currentrow = myreader.ReadFields()?


Solution

  • You can use File.AppendAllText to add the quote:

    File.AppendAllText(filePath, """")