Martin Dreher Martin Dreher - 2 months ago 21
Vb.net Question

TextFieldParser not skipping .CommentTokens-Lines

Following this, I use a

TextFieldParser
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() {"'"}
Debug.Print(.ReadToEnd)
' 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:

'comment1
1;0.5;0.9;0.3
0.5;1;0.6;0.2
0.9;0.6;1;0.1
0.3;0.2;0.1;1


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

Answer

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
    Try
        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
Comments