Thursday, December 9, 2010

How to upload / download / delete file using FTP in asp.net / vb.net

We can easily upload or download files from FTP using asp.net/vb.net:


To Upload file to FTP/Remote Server using VB.NET

Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
Dim myStreamWriter As StreamWriter

myFtpWebRequest = WebRequest.Create("ftp://ftp_server_name/filename.ext")

'myFtpWebRequest.Credentials = New NetworkCredential("username", "password")

myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True

myStreamWriter = New StreamWriter(myFtpWebRequest.GetRequestStream())
myStreamWriter.Write(New StreamReader(Server.MapPath("filename.ext")).ReadToEnd)
myStreamWriter.Close()

myFtpWebResponse = myFtpWebRequest.GetResponse()

litResponse.Text = myFtpWebResponse.StatusDescription

myFtpWebResponse.Close()
End Sub


To Download file from FTP/Remote Server using VB.NET

Protected Sub btnDownloadFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
Dim myStreamWriter As StreamWriter

myFtpWebRequest = WebRequest.Create("ftp://ftp_server_name/filename.ext")

'myFtpWebRequest.Credentials = New NetworkCredential("username", "password")

myFtpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile
myFtpWebRequest.UseBinary = True

myFtpWebResponse = myFtpWebRequest.GetResponse()

myStreamWriter = New StreamWriter(Server.MapPath("filename.ext"))
myStreamWriter.Write(New StreamReader(myFtpWebResponse.GetResponseStream()).ReadToEnd)
myStreamWriter.Close()

litResponse.Text = myFtpWebResponse.StatusDescription

myFtpWebResponse.Close()
End Sub

To Delete file from FTP/Remote Server using VB.NET

Protected Sub btnDeleteFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse

myFtpWebRequest = WebRequest.Create("ftp://ftp_server_name/filename.ext")

'myFtpWebRequest.Credentials = New NetworkCredential("username", "password")

myFtpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile

myFtpWebResponse = myFtpWebRequest.GetResponse()

litResponse.Text = myFtpWebResponse.StatusDescription

myFtpWebResponse.Close()
End Sub

Share This!


1 comment:

Anonymous said...

Nice tutorial, but how do you
list directories and files

thanks nameless

Powered By Blogger · Designed By Seo Blogger Templates