2016-09-19 134 views
0

我通過循環讀取並使用Streamreader讀取行來解析平面文件。VB .Net Streamreader - 在文本文件中的換行符之前修剪空格

一切正常,但需求更改,每個記錄末尾的字段變爲可選。我們根據定義驗證每行的長度,以確定是否應將該文件暫掛爲格式不正確。

這導致發現Streamreader.ReadLine將修剪最後一個字符之後和換行符之前的任何尾隨空格。

考慮具有由空格置換的數字下面的例子:

鮑勃·瓊斯12345 \ n 鮑勃·瓊斯\ n

的StreamReader的將與兩者的ReadLine和ReadToEnd的商店忽略這些位。下面是結果存儲:

的Readline:

「鮑勃·瓊斯12345」 「鮑勃·瓊斯」

ReadToEnd的:

「鮑勃·瓊斯12345」 & vbrclf & 「鮑勃·瓊斯」

與Readblock相同,然後將緩衝區結果複製到一個字符串中。

我會採取不同的方法來驗證記錄的長度,因爲結束日期字段是可選的,但我的問題是爲什麼Streamreader會丟棄這些結束空格?如果我需要,我將如何閱讀他們?

+1

我非常驚訝這種行爲,所以測試它。至少默認情況下,對於我來說,StreamReader.ReadLine不會這樣做。你確定代碼修剪中沒有其他東西嗎?你能夠重現小代碼示例中的行爲嗎?你能否確認你使用的.Net版本? – tolanj

回答

0

StreamReader不會修剪的空格,其可以方便地與一個樣本程序看到這樣

Imports System.IO 

Module Module1 

    Sub Main() 
     Dim sr As StreamReader = New StreamReader("SampleTextFile.txt") 
     Dim text As String = sr.ReadToEnd 

     Console.WriteLine("Original text") 
     Console.WriteLine(text) 
     Console.WriteLine() 

     Console.WriteLine("White-spaces as .") 
     Console.WriteLine(text.Replace(" ", ".")) 
     Console.WriteLine() 

     Console.ReadKey() 
    End Sub 

End Module 

和對應SampleTextFile.txt因爲這

Some text with 2 white-spaces at the end 
Some other text with one white-space at the end 
No whit-espace at the end 
Next line will be made of white-spaces 

The EN 

,這將導致在這個輸出

Original text 
Some text with 2 white-spaces at the end 
Some other text with one white-space at the end 
No whit-espace at the end 
Next line will be made of white-spaces 

The END 

White-spaces as . 
Some.text.with.2.white-spaces.at.the.end.. 
Some.other.text.with.one.white-space.at.the.end. 
No.whit-espace.at.the.end 
Next.line.will.be.made.of.white-spaces 
......... 
The.END 

所以你可能想檢查你的親克再次在那裏你可以自己修剪絃樂。

+0

你是對的,早期的一點修剪它。謝謝! – crayfin

+0

很高興聽到 - 請接受答案(通過綠色複選標記) - thx – DAXaholic

相關問題