如何使用.net下载GZ格式的ftp文件

时间:2016-03-30 17:07:14

标签: .net vb.net file ftp binary

当我以.gz格式从FTP成功下载文件时,该文件已损坏。这是我的代码:

Public Sub DLFile(FName As String)
    Dim URI = _Host & "/" & _RemoteDir & "/" & FName
    Dim Dest = _LocalDir & "\V7`0_" & FName

    _Response = FTP_Transact(WebRequestMethods.Ftp.DownloadFile, URI)
    Using reader = New StreamReader(_Response.GetResponseStream)
        Using writer = New StreamWriter(Dest, append:=False)
            writer.Write(reader.ReadToEnd())
        End Using
    End Using
End Sub

Private Function FTP_Transact(What As String, URI As String) As System.Net.FtpWebResponse
    _Request = DirectCast(WebRequest.Create(URI), FtpWebRequest)
    _Request.Method = What
    _Request.UseBinary =True
    _Request.Credentials = _Credentials
    FTP_Transact = DirectCast(_Request.GetResponse(), FtpWebResponse)
End Function

我意识到它使用的是Ascii传输而不是二进制,但我不知道如何改变它。 StreamReader和StreamWriter需要被什么??

取代

更新:小变化解决了问题 @Eser钉了它!完成的代码如下所示:

Public Sub DLFile(FName As String)
    Dim URI = _Host & "/" & _RemoteDir & "/" & FName
    Dim Dest = _LocalDir & "\V7`0_" & FName

    _Response = FTP_Transact(WebRequestMethods.Ftp.DownloadFile, URI)
    If File.Exists(Dest) Then File.Delete(Dest)
    Using writer = New FileStream(Dest, FileMode.Create)
        _Response.GetResponseStream().CopyTo(writer)
    End Using
End Sub

0 个答案:

没有答案