vb.net从.txt文件读取并显示内容 [英] vb.net Reading from a .txt file and displaying the contents
问题描述
我正在制作一个简单的程序,可以读写.txt文件.我有要写入和保存.txt文件的程序,但是从.txt文件读取时遇到了一些麻烦.这是到目前为止我得到的:
I'm making a simple program which reads and writes .txt files. I've got the program to write to and save a .txt file however I'm having some trouble reading from .txt files. Here's what I've got so far:
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
我想发生的是,当文本被读取后,它会填充在另一个窗体(displayForm)内的列表框中.我尝试使文本以相同的形式显示在列表框中,以查看是否可能已更改任何内容,但仍保持空白.我可以确认我只用.txt文件进行过测试,因为在此阶段我没有进行任何错误检查.非常感谢您的帮助!
What I would like to happen is when the text has been read it populates in a list box which is present inside another form (displayForm). I've tried getting the text to display in a listbox on the same form to see if that might have changed anything but it still remains blank. I can confirm that I've only ever tested it with .txt files as I've put no error checking in at this stage. Many thanks for any help!
推荐答案
ListBox
不是用于显示文本,而是用于显示列表(顾名思义).如果要显示文本,请使用TextBox
.由于文件可能包含多行,因此可以将.Multiline
属性设置为True
,以便TextBox
可以正确显示它.
A ListBox
is not for displaying text, but displaying lists (as the name suggests). If you want to display text, use a TextBox
. Since it is likely that the file will contain multiple lines, you can set the .Multiline
property to True
, so that the TextBox
will display it correctly.
此外,在处理Streams
Dim content As String = ""
Using textReader As New System.IO.StreamReader(openTxt.FileName)
content = textReader.ReadToEnd
End Using
displayForm.ListBox1.Text = content
或仅使用System.IO.File.ReadAllText("path to file here")
命令.
这篇关于vb.net从.txt文件读取并显示内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!