我发现此代码可以从FTP中的目录和子目录下载图像文件:
C# Download all files and subdirectories through FTP
所以这是我在VB.NET中的代码:
Private Sub DownloadFtpDirectory(ByVal url As String, ByVal credentials As NetworkCredential, ByVal localPath As String)
Dim listRequest As FtpWebRequest = CType(WebRequest.Create(url), FtpWebRequest)
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
listRequest.Credentials = credentials
Dim lines As List(Of String) = New List(Of String)
Dim listResponse As FtpWebResponse = CType(listRequest.GetResponse, FtpWebResponse)
Dim listStream As Stream = listResponse.GetResponseStream
Dim listReader As StreamReader = New StreamReader(listStream)
While Not listReader.EndOfStream
lines.Add(listReader.ReadLine)
End While
For Each line As String In lines
Dim tokens As String() = line.Split({" "}, 9, StringSplitOptions.RemoveEmptyEntries)
Dim name As String = tokens(8)
Dim permissions As String = tokens(0)
Dim localFilePath As String = Path.Combine(localPath, name)
Dim fileUrl As String = (url + name)
If (permissions(0) = ChrW(100)) Then
If Not Directory.Exists(localFilePath) Then
Directory.CreateDirectory(localFilePath)
End If
DownloadFtpDirectory((fileUrl + "/"), credentials, localFilePath)
Else
Dim downloadRequest As FtpWebRequest = CType(WebRequest.Create(fileUrl), FtpWebRequest)
downloadRequest.Credentials = credentials
downloadRequest.KeepAlive = False
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
downloadRequest.UseBinary = True
downloadRequest.Proxy = Nothing
downloadRequest.UsePassive = False
Dim downloadResponse As FtpWebResponse = CType(downloadRequest.GetResponse, FtpWebResponse)
Dim sourceStream As Stream = downloadResponse.GetResponseStream
Dim targetStream As FileStream = New FileStream(localFilePath, FileMode.Create)
Dim buffer() As Byte = New Byte((10240) - 1) {}
Dim read As Integer
While (sourceStream.Read(buffer, 0, buffer.Length) > 0)
targetStream.Write(buffer, 0, read)
End While
End If
Next
End Sub
我用这个方法调用函数:
Private Sub btnDownloadImagesFromFTP_Click(sender As Object, e As EventArgs) Handles btnDownloadImagesFromFTP.Click
Try
Dim credentials As NetworkCredential = New NetworkCredential("user", "password")
Dim url As String = "ftp://myftp/imagesDirectory/"
DownloadFtpDirectory(url, credentials, "C:\Users\Admin\Desktop\imagesFromFTP")
Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
End Try
End Sub
代码正常运行并下载带有图像文件和名称的子目录,但是当我打开任何图像时,它是空的(0字节)
任何人都知道为什么会这样?感谢。
答案 0 :(得分:1)
您永远不会分配read
变量。
While ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)