'Add StreamReader contents with FTP directory listing to a ListBox in VB.NET?

This is the code I have so far

Dim listRequest As FtpWebRequest = WebRequest.Create("ftp://ftpserver.com/folder/")
listRequest.Credentials = New NetworkCredential(ftp_user, ftp_pass)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim listResponse As FtpWebResponse = listRequest.GetResponse()
Dim reader As StreamReader = New StreamReader(listResponse.GetResponseStream())
ListBox1.Items.AddRange(reader.ReadToEnd())
MessageBox.Show(reader.ReadToEnd())

I am very confused on how I can put the contents of the reader.ReadToEnd in a ListBox. If anyone can assist me with this issue it would be greatly appreciated.



Solution 1:[1]

Read the stream line-by-line using StreamReader.ReadLine

ListBox1.BeginUpdate()
Try
    Dim line As String
    While True
        line = reader.ReadLine()
        If line IsNot Nothing Then
            ListBox1.Items.Add(line)
        Else
            Exit While
        End If
    End While
Finally
    ListBox1.EndUpdate()
End Try

If performance when dealing with huge amount of files is not a concern, the following inefficient but short code will do the same:

ListBox1.Items.AddRange(
    reader.ReadToEnd().Split(
        New String() {vbCrLf}, StringSplitOptions.RemoveEmptyEntries))

Note that you should be doing network operations on a background thread, but that's for a separate question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1