我正在尝试熟悉网络编程,还有什么比设计 FTP 客户端代码库更好的起点呢?
到目前为止,我做得不是很好。我正在尝试创建一种将文件从远程服务器下载到本地文件路径的方法。为此,我能找到的所有示例都声明了一个用作数据缓冲区的字节数组。我完全理解这样做的意义,而不是每个字节读取和写入字节,但我就是无法让它工作。每当我设置大于 1 字节的缓冲区时,输出都会以某种方式损坏(不同的校验和,媒体文件无法播放等)。
有人可以指出我在这里做错了什么:
Public Function DownloadFile(source As Uri, output As Uri) As FtpStatusCode
Dim request = FtpWebRequest.Create(source)
request.Method = WebRequestMethods.Ftp.DownloadFile
Using response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
Using outputStream = New FileStream(output.AbsolutePath, FileMode.Create)
Do
Dim buffer(8192) As Byte
response.GetResponseStream.Read(buffer, 0, buffer.Length)
outputStream.Write(buffer, 0, buffer.Length)
Loop While outputStream.Position < response.ContentLength
End Using
Return response.StatusCode
End Using
End Function
因为当我将缓冲区大小设置为 1 时这段代码确实有效,所以我觉得字节顺序有问题。但是所有这些代码都是同步的,所以这怎么可能......
编辑
我现在可以使用它,所以这是供将来参考的代码解决方案(再次感谢@tcarvin):
Public Function DownloadFile(source As Uri, output As Uri) As FtpStatusCode
Dim request = FtpWebRequest.Create(source)
request.Method = WebRequestMethods.Ftp.DownloadFile
Using response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
Using inputStream = response.GetResponseStream
Using outputStream = New FileStream(output.AbsolutePath, FileMode.Create)
Do
Dim buffer(8192) As Byte
Dim buffered = inputStream.Read(buffer, 0, buffer.Length).Read(buffer, 0, buffer.Length)
outputStream.Write(buffer, 0, buffered)
Loop While outputStream.Position < response.ContentLength
End Using
End Using
Return response.StatusCode
End Using
End Function