2010-11-16 60 views
6

我使用VB.NET的TextFieldParser(Microsoft.VisualBasic.FileIO.TextFieldParser)來讀取分隔文件。但是,當我嘗試在字段中連續換行的字段中讀取時,連續換行符會變成一個新行。我希望保留連續的換行符,但我不確定如何。爲什麼TextFieldParser.ReadField從字段中間刪除連續的換行符?

下面是一個示例文件,我正在閱讀一個字段。該報價是該文件的內容的一部分,有三個新行(包括下面的第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. 

我能做些什麼來保持連續的換行?

+2

我有同樣的問題,並且已經向Microsoft提交了一個錯誤報告:https://connect.microsoft.com/VisualStudio/feedback/details/679596/textfieldparser-does-not-respect-consecutive-line-breaks -in最中間,一個場 – 2011-07-16 05:12:10

回答

2

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

如果閱讀字段遇到空行, 他們被跳過,返回下一 非空行。

我相信你要做的就是使用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 
0

也許你可以看看 「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(); 
} 

我沒有在最後測試的空行的所有邊緣案件等等。

相關問題