TextFieldParser没有跳过.CommentTokens-Lines

时间:2016-09-12 09:09:28

标签: vb.net visual-studio-2010

关注this后,我使用TextFieldParser来读取csv文件:

    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

设置.CommentTokens = New String() {"'"}后,我跳过了预期带有单引号的行。

但是,从我收集的内容来看,阅读csv时没有任何区别:

'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

我尝试将单引号'替换为几个常见的评论字符(#\\*),无论是否有以下空白 - 仍然没有获得理想的结果。

1 个答案:

答案 0 :(得分:1)

在您的代码中,您使用的是TextFieldParser.ReadToEnd,它只返回完整的剩余文本,并且不会忽略注释。记录在案:

  

ReadToEnd方法不会忽略空白行和注释。

如果您使用ReadFields,评论将被忽略(MS示例):

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
相关问题