Monday, September 20, 2010

VB.NET Download/Upload From FTP

//download

Private Sub ftpp()
Dim localFile As String = "C:\Inetpub\wwwroot\order\images\updatemaster.mdb"
Dim remoteFile As String = "/kapil/updatemaster.mdb"
Dim host As String = "ftp://ftp.sdmftp.com"
Dim URI As String = host & remoteFile
Dim username As String
Dim password As String
username = "rpc"
password = "rpc123"
Dim ftp As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)
ftp.Credentials = New System.Net.NetworkCredential(username, password)
ftp.KeepAlive = False
ftp.UseBinary = True
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = _
CType(ftp.GetResponse, System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
'loop to read & write to file
Using fs As New IO.FileStream(localFile, IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 0
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0 'see Note(1)
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
MsgBox("downloaded")
End Sub

//Upload
Private Sub ftppu()
Dim localFile As String = "C:\Inetpub\wwwroot\order\images\updatemaster.mdb"
Dim remoteFile As String = "/kapil/updatemaster.mdb"
Dim host As String = "ftp://ftp.sdmftp.com"
Dim URI As String = host & remoteFile
Dim username As String
Dim password As String
username = "rpc"
password = "rpc123"

Dim reqObj As FtpWebRequest = WebRequest.Create(URI)
reqObj.Method = WebRequestMethods.Ftp.UploadFile
reqObj.Credentials = New NetworkCredential(username, password)
Dim streamObj As FileStream = File.OpenRead(localFile)
Dim buffer(streamObj.Length) As Byte
streamObj.Read(buffer, 0, buffer.Length)
streamObj.Close()
streamObj = Nothing
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length)
reqObj = Nothing
End Sub

No comments: