Understand ftp with asp.net in 5 Minutes Part- IInd

Hello Friends,

 In last article we have did how to upload a file I know you are very eager to know how to download a file.  I am not taking much time here and will introduce you below code by which you can download a file. It just likes our earlier upload ftp file.Its screen is just like below.

  DownloadFTP

On the button click we did following thing

  Protected Sub btnDownload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDownload.Click

        Try

            Dim ftpRes As FtpWebRequest = DirectCast(FtpWebRequest.Create(Me.txtFtp.Text & “/” & Me.txtRemoteFileName.Text), FtpWebRequest)

            ftpRes.Credentials = New NetworkCredential(Me.txtUserName.Text, Me.txtPassword.Text)

            ftpRes = DirectCast(WebRequest.Create(Me.txtFtp.Text & “/” & Me.txtRemoteFileName.Text), FtpWebRequest)

            ftpRes.Credentials = New NetworkCredential(Me.txtUserName.Text, Me.txtPassword.Text)

            ftpRes.Method = WebRequestMethods.Ftp.DownloadFile

            ftpRes.UseBinary = True

            Dim myFtpWebResponse As FtpWebResponse = ftpRes.GetResponse()

            Dim myStreamWriter As StreamWriter

            myStreamWriter = New StreamWriter(“c:\Downloads\” & Me.txtRemoteFileName.Text)

            myStreamWriter.Write(New StreamReader(myFtpWebResponse.GetResponseStream()).ReadToEnd)

            myStreamWriter.Close()

            myFtpWebResponse.Close()

        Catch eh As System.Net.WebException

            Response.Write(eh.Message)

        Catch ex As Exception

            Throw ex

        End Try

    End Sub

Here  The main important thing is method which is download file as you see in above code.

We just take response of ftp and read the stream of this with the help of GetResponseStream().ReadToEnd.

Rest all the thing is same like our old code for file upload.

I hope you got with the above code. 

Thanks & Enjoy coding

Your host

Rajat Jaiswal

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s