2016-09-19 28 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

相关问题