gpt4 book ai didi

.net - 为什么TextFieldParser.ReadField从字段中间删除连续的换行符?

转载 作者:行者123 更新时间:2023-12-04 15:48:28 26 4
gpt4 key购买 nike

我正在使用VB.NET的TextFieldParser(Microsoft.VisualBasic.FileIO.TextFieldParser)读取分隔的文件。但是,当我尝试在该字段中包含连续换行符的字段中读取时,连续换行符会变成一条新换行。我希望保留连续的换行符,但是不确定如何保存。

这是我正在读取的一个示例文件,其中仅包含一个字段。引号是文件内容的一部分,并且包含三个换行符(包括第二行之后的两个连续换行符):

"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)

这是“line”变量的内容。请注意,现在只有两条换行符:
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

关于.net - 为什么TextFieldParser.ReadField从字段中间删除连续的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4197942/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com