Reputation: 459
This is my code and I want to read my TestFile.txt file and display it in txt2.Text, but this code doesn't read my txt file. anyone could help me to fixed this problem ? Thanks
Dim MyFileName As String = "C:\Users\TestFile.txt"
Dim Line As String = ""
Dim sb As New StringBuilder
Using sr As New StringReader(MyFileName)
Line = sr.ReadLine
Do
If Line = "*" Then
Line = sr.ReadLine
Do
sb.Append(LineRead)
Line = sr.ReadLine
Loop Until Line = "**"
End If
Line = sr.ReadLine
Loop Until Line = ""
End Using
Line = txt2.Text
Upvotes: 0
Views: 2327
Reputation: 56697
You do not append Line
to the StringBuilder
, but LineRead
, which is not set in your code.
Your code should read:
Line = sr.ReadLine
Do
sb.Append(Line)
Line = sr.ReadLine
Loop Until Line = "**"
In the comments I've been advised to remove the following bit from my answer:
The real problem are programming languages that don't force you to declare variables before you can use them. You gotta love VB.NET...
I'd like to quote the MSDN here:
By default, the Visual Basic .NET or Visual Basic compiler enforces explicit variable declaration, which requires that you declare every variable before you use it. To change this default behavior, see the Change the Default Project Values section.
So, while by default the commenter is right, you can change the behavior, and nothing in the question tells me the OP didn't change it. Still, I'll rephrase my statement to be more precise:
The real problem are programming languages that allow you to turn of the need to declare variables before you can use them. You gotta love VB.NET...
Upvotes: 1
Reputation: 229058
StringReader just lets you read from a string, it doesn't read or open a file.
Use a StreamReader to read from a file.
Dim filename As String = "C:\Users\TestFile.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) ' you probably meant Line, not LineRead
Line = sr.ReadLine
Loop Until Line = "**"
End If
Line = sr.ReadLine
Loop Until Line = ""
End Using
Upvotes: 1