Why does TextFieldParser.ReadField remove consecutive newlines from the middle of a field?

I am using VB.NET TextFieldParser (Microsoft.VisualBasic.FileIO.TextFieldParser) to read a delimited file. However, when I try to read in a field with consecutive news in a field, consecutive lines of a new line turn into one new line. I would like consecutive lines to be saved, but I'm not sure how to do this.

Here is an example file that I am reading with one field. The quotation marks are part of the contents of the file, and there are three newlines (including two consecutive newlines, following line 2):

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

Here is the code that I use to parse and read in a file:

 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) 

And here is the contents of the variable "string". Note that now there are only two lines:

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

What can I do to save consecutive lines of a new line?

+6
string file-io parsing
source share
2 answers

First, according to MSDN http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.readfields.aspx blank lines are ignored:

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

I believe that you will need to use ReadLine http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.readline.aspx and then view the results.

 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
source share

Perhaps you can see the property "LineNumber"? ...

(FROM#)

 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(); } 

I have not tested all extreme cases of empty lines at the end, etc.

0
source share

All Articles