加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

.net – 为什么TextFieldParser.ReadField从字段中间删除连续的

发布时间:2020-12-17 00:11:07 所属栏目:大数据 来源:网络整理
导读:我使用VB.NET的TextFieldParser(Microsoft.VisualBasic.FileIO.TextFieldParser)来读取分隔文件.但是,当我尝试在字段中读取具有连续换行符的字段时,连续的换行符将变为单个新行.我希望保留连续的换行符,但我不确定如何. 这是我正在阅读的一个示例文件,只有一
我使用VB.NET的TextFieldParser(Microsoft.VisualBasic.FileIO.TextFieldParser)来读取分隔文件.但是,当我尝试在字段中读取具有连续换行符的字段时,连续的换行符将变为单个新行.我希望保留连续的换行符,但我不确定如何.

这是我正在阅读的一个示例文件,只有一个字段.引号是文件内容的一部分,有三个换行符(包括第2行后的两个连续换行符):

"This is line 1
This is line 2

This is line 4,which follows two consecutive newlines."

这是我用来解析和读取文件的代码:

Dim reader as New Microsoft.VisualBasic.FileIO.TextFieldParser(myFile,System.Text.Encoding.Default)
reader.TextFieldType = FileIO.FieldType.Delimited
reader.SetDelimiters(",")

Dim fields As String() = reader.ReadFields
Dim line As String = fields(0)

这是“行”变量的内容.请注意,现在只有两个新行:

This is line 1
This is line 2
This is line 4,which follows two consecutive newlines.

我该怎么做才能保留连续的换行符?

首先,根据MSDN http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.readfields.aspx空白行被忽略:

If ReadFields encounters blank lines,
they are skipped and the next
non-blank line is returned.

我相信你需要做的是使用ReadLine http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.readline.aspx然后循环结果.

Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:ParserText.txt")
    MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
    MyReader.Delimiters = New String() {","}
    Dim currentRow As String
    While Not MyReader.EndOfData
        Try
            currentRow = MyReader.ReadLine()
            'Manipulate line...
        Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & " is invalid.  Skipping")
        End Try
    End While
End Using

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读