【问题标题】:Why does TextFieldParser.ReadField remove consecutive newlines from middle of a field?为什么 TextFieldParser.ReadField 从字段中间删除连续的换行符?
【发布时间】:2010-11-16 19:03:15
【问题描述】:

我正在使用 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)

这里是“line”变量的内容。请注意,现在只有两个换行符:

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

我可以做些什么来保留连续的换行符?

【问题讨论】:

标签: .net vb.net parsing string file-io


【解决方案1】:

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

如果 ReadFields 遇到空行, 他们被跳过,下一个 返回非空行。

我相信您需要做的是使用 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

【讨论】:

    【解决方案2】:

    您也许可以查看“LineNumber”属性?...

    (c#)

    var beforeRead = _parser.LineNumber;
    _parser.ReadFields();
    var afterRead = _parser.LineNumber;
    
    if(afterRead <= -1)
       lineNumber = beforeRead;
    else                    
       lineNumber = afterRead - 1;
    
    for (var blankLines = beforeRead; blankLines < afterRead-1; blankLines++)
    {
        Console.WriteLine();
    }
    

    我还没有测试最后的空白行的所有边缘情况等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多