0

I'm using vb.net. Below is my code on read a txt file and my txt file is quite large. I successfully read and display my Test.txt in txt2.Text, I want my output inside the Test.txt same line by line to be display inside the txt2.Text, I have set up my txt2.Text as multiple line. So when i enlarge my txt2.Text, my output will be the same as inside the Test.txt file. how do i used VbCrLf inside my code?

Dim filename As String = "C:\Users\user\Documents\Test.txt"
Dim Line As String = ""
Dim sb As New StringBuilder
Using sr As StreamReader = File.OpenText(filename)
   Line = sr.ReadLine
        Do
            If Line = "*" Then
                Line = sr.ReadLine
                Do
                    sb.Append(Line)     
                    Line = sr.ReadLine
                Loop Until Line = "**"
            End If
            Line = sr.ReadLine
        Loop Until Line = ""
    End Using
    txt2.Text = sb.ToString
End Sub
4

2 回答 2

1

您的循环从输入行中删除 CarriageReturn 和 LineFeed 字符。
你可以阅读他们改变这一行

sb.Append(Line)

sb.AppendLine(Line)

但是你很快就会发现你有一个更大的问题。
在循环内,您执行各种 ReadLine 而不检查您是否真的有另一行可供阅读。我不知道您文件的结构,但建议进行某种错误检查。

于 2013-09-30T16:01:43.567 回答
0

使用这样的文本文件:

testdata10
*
testdata1
    testdata2
        testdata3
testdata4
testdata5
**
testdata11

*假设在到达之前没有更多**内容,此代码将按原样将适当的行添加到文本框中:

    Using sr As New IO.StreamReader("textfile1.dat")
        Dim line As String = ""
        While Not sr.EndOfStream
            line = sr.ReadLine
            If line = "*" Then
                Do
                    TextBox1.AppendText(sr.ReadLine & vbNewLine)
                Loop Until sr.Peek = Asc("*"c)
            End If
        End While
    End Using
于 2013-09-30T17:06:07.423 回答