这是我的代码,我想读取我的TestFile.txt文件并将其显示在txt2.Text中,但此代码不会读取我的txt文件。有人可以帮我解决这个问题吗?感谢
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
答案 0 :(得分:1)
您不会将Line
附加到StringBuilder
,而是附加LineRead
,而不会在您的代码中设置。
您的代码应为:
Line = sr.ReadLine
Do
sb.Append(Line)
Line = sr.ReadLine
Loop Until Line = "**"
在评论中,我被建议从我的回答中删除以下内容:
真正的问题是编程语言,在您使用它们之前不会强制您声明变量。你一定要喜欢VB.NET ......
我想在这里引用MSDN:
默认情况下,Visual Basic .NET或Visual Basic编译器强制显式变量声明,这要求您在使用之前声明每个变量。要更改此默认行为,请参阅更改默认项目值部分。
所以,默认情况下,评论者是对的,你可以改变行为,问题中没有任何内容告诉我OP没有改变它。不过,我会更加确切地说明我的陈述:
真正的问题是编程语言,它允许您在使用它们之前转换声明变量的需要。你一定要喜欢VB.NET ......
答案 1 :(得分:1)
StringReader只允许您从字符串中读取,它不会读取或打开文件。
使用StreamReader从文件中读取。
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