vb.net从.txt文件读取并显示内容

Nov*_*orm 1 vb.net file streamreader

我正在做一个简单的程序,可以读写.txt文件。我有要写入并保存.txt文件的程序,但是从.txt文件读取时遇到了一些麻烦。到目前为止,这是我得到的:

Using openTxt As New OpenFileDialog()
    If openTxt.ShowDialog() = Windows.Forms.DialogResult.OK Then
        Dim displayForm As New Form
        Dim textReader As New System.IO.StreamReader(openTxt.FileName)
        displayForm.ListBox1.Text = textReader.ReadToEnd
        textReader.Close()
        displayForm.Show()
    Else
        MessageBox.Show("Not a text file")
    End If
End Using
Run Code Online (Sandbox Code Playgroud)

我想发生的是,当文本被读取时,它会填充在另一个窗体(displayForm)内的列表框中。我尝试使文本以相同的形式显示在列表框中,以查看是否可能已更改任何内容,但仍保持空白。我可以确认我只用.txt文件进行过测试,因为在此阶段我没有进行任何错误检查。非常感谢您的帮助!

WeS*_*eSt 5

A ListBox不是显示文本,而是显示列表(顾名思义)。如果要显示文本,请使用TextBox。由于文件可能包含多行,因此您可以将.Multiline属性设置为True,以便TextBox可以正确显示它。

此外,您using statement在处理时应使用Streams

Dim content As String = ""
Using textReader As New System.IO.StreamReader(openTxt.FileName)
  content = textReader.ReadToEnd
End Using
displayForm.ListBox1.Text = content
Run Code Online (Sandbox Code Playgroud)

或者只是使用System.IO.File.ReadAllText("path to file here")命令。