vb.net Reading from a .txt file and displaying the

2019-05-30 05:47发布

问题:

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

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!

回答1:

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.

Furthermore, you should use the using statement when dealing with Streams

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

or simply use the System.IO.File.ReadAllText("path to file here") command.



回答2:

Do you want to read the file line-by-line and populate the listbox control?

If that's the case then try this function

Function ReadFile(ByVal Filename As String) As String()
    Dim Sl As New List(Of String)
    Using Sr As New StreamReader(Filename)
        While Sr.Peek >= 0
            Sl.Add(Sr.ReadLine())
        End While
    End Using
    Return Sl.ToArray
End Function

And use like so:

    For Each Line As String In ReadFile("FILENAME.txt")
        ListBox1.Items.Add(Line)
    Next