Loading file contents from FTP to ListBox

故事扮演 提交于 2019-12-04 18:34:53

To read a file contents, you have to use DownloadFile method, not ListDirectory:

Dim request As FtpWebRequest = WebRequest.Create("ftp://example.com/path/Ann.txt")
request.Method = WebRequestMethods.Ftp.DownloadFile
request.Credentials = New NetworkCredential("username", "password")

Using response As FtpWebResponse = request.GetResponse(),
      stream As Stream = response.GetResponseStream(),
      reader As StreamReader = New StreamReader(stream)
    While Not reader.EndOfStream
        ListBox1.Items.Add(reader.ReadLine())
    End While
End Using

Also note:

  • the use of Using statement;
  • no need for intermediate ArrayList().

Due to crappy implementation of the Stream returned by .GetResponseStream, the code will not work correctly if the last line is not terminated by a new line. Working this around would require much more complicate code. See also StreamReader ReadLine throwing disposed exception rather than returning null (not exactly the same problem, but similar).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!