Martin Dreher Martin Dreher - 5 months ago 54 Question

TextFieldParser not skipping .CommentTokens-Lines

Following this, I use a

to read a csv File:

Sub imp1(path As String)
With New TextFieldParser("C:\matrix1.csv")
.TextFieldType = FileIO.FieldType.Delimited
.Delimiters = New String() {";"}
.CommentTokens = New String() {"'"}
' some more code to read the contents into a 2d-array
End with
End Sub

After setting
.CommentTokens = New String() {"'"}
I expected lines with leading single quotes being skipped.

However, from what I gather there is no difference at all when reading a csv like the following:


I tried replacing the single quote
with several common comment-characters (
), both with and without a following blanks - still not getting the desired results.


In your code you are using TextFieldParser.ReadToEnd which simply returns the complete remaining text and does not ignore comments. This is documented:

The ReadToEnd method does not ignore blank lines and comments.

If you would use ReadFields the comments would be ignored (MS example):

While Not MyReader.EndOfData
        currentRow = MyReader.ReadFields()
        ' Include code here to handle the row.
    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
        MsgBox("Line " & ex.Message & 
        " is invalid.  Skipping")
    End Try
End While