如何列出FTP连接的目录内容

时间:2012-12-28 23:15:53

标签: vb.net ftp

我找不到相关的教程。在VB.NET中,我想做一个命令,如:

Dim array1() as string = ListFilesInFolder("www.example.com/images")

我知道这可能不会那么简单,但任何人都可以指点教程或其他什么吗?

2 个答案:

答案 0 :(得分:8)

使用此免费库http://netftp.codeplex.com/

Imports System.Net
Imports System.Net.FtpClient

Sub Main
    using ftp = new FtpClient()

        ftp.Host = "www.example.com"
        ftp.Credentials = new NetworkCredential("yourFTPUser", "yourFTPPassword")
        ftp.SetWorkingDirectory("/images")
        for each item in ftp.GetListing(ftp.GetWorkingDirectory())

            select case item.Type
                case FtpFileSystemObjectType.Directory:
                    Console.WriteLine("Folder:" + item.FullName)
                case FtpFileSystemObjectType.File:
                    Console.WriteLine("File:" + item.FullName)
            End Select
        Next
    End Using    
End Sub

当然我假设www.example.com是一个FTP服务器。

重要提示:图书馆需要完整的Framework 4.0。您应该转到Project Properties的构建页面,点击Advanced Options并选择Framework 4.0而不是Framework 4.0 Client Profile

答案 1 :(得分:2)

以下方法适用于framework 3.5及更高版本,我知道这个问题是3年但我遇到了需要在framework 3.5项目中列出FTP目录的情况所以我写了以下代码通过引用How to: List Directory Contents with FTP

Imports System.Net

Dim Dirlist As New List(Of String) 'I prefer List() instead of an array
Dim request As FtpWebRequest = DirectCast(WebRequest.Create("ftp://www.example.com/images"), FtpWebRequest)

request.Method = WebRequestMethods.Ftp.ListDirectory
request.Credentials = New NetworkCredential("USER_NAME", "PASSWORD")

Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Dim responseStream As Stream = response.GetResponseStream

    Using reader As New StreamReader(responseStream)
          Do While reader.Peek <> -1
             Dirlist.Add(reader.ReadLine)
          Loop
    End Using
response.Close()