0

这是我的代码,我想读取我的 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
4

2 回答 2

1

您不附加Line到代码中未设置的StringBuilder, but 。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...

于 2013-09-27T07:22:39.420 回答
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
于 2013-09-27T07:26:20.383 回答