【问题标题】:VB .Net Streamreader - Trimming spaces before newline in text fileVB .Net Streamreader - 在文本文件中的换行符之前修剪空格
【发布时间】:2017-01-27 03:18:31
【问题描述】:

我通过使用 Streamreader 循环和读取行来解析平面文件。

一切正常,但要求发生了变化,每条记录末尾的字段变为可选。我们根据定义验证每一行的长度,以确定我们是否应该将该文件挂起为格式不正确。

这导致发现 Streamreader.ReadLine 将修剪最后一个字符之后和换行符之前的所有尾随空格。

考虑以下用空格替换数字的示例:

鲍勃·琼斯 12345\n 鲍勃·琼斯 \n

ReadLine 和 ReadToEnd 存储的流读取器将忽略这些空格。这是内存中的结果:

阅读:

“鲍勃·琼斯 12345” “鲍勃·琼斯”

ReadToEnd:

“鲍勃·琼斯 12345”和 vbrclf 和“鲍勃·琼斯”

同样处理 Readblock,然后将缓冲区结果复制到字符串中。

我将采用不同的方法来验证记录的长度,因为结束日期字段是可选的,但我的问题是为什么 Streamreader 会删除这些结束空格?如果需要,我将如何阅读它们?

【问题讨论】:

  • 我对这种行为非常感到惊讶,因此对其进行了测试。至少默认情况下,对我来说, StreamReader.ReadLine 不会这样做。你确定你的代码修剪中没有别的东西吗?您是否能够在一个小代码示例中重现该行为?您能确认您使用的 .Net 版本吗?

标签: .net vb.net streamreader trim


【解决方案1】:

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

所以你可能想再次检查你的程序,你可以自己修剪字符串。

【讨论】:

    猜你喜欢
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多