Code Repo    |     RSS
MD's Technical Sharing



Saturday, January 17, 2009

Upload a file to FTP

See: http://msdn.microsoft.com/en-us/library/ms229715.aspx


'upload a file via FTP
'return TRUE if OK, FALSE if error
'subdir: the sub-directory (to be created on the server) to put the uploaded file in
Function UploadFileToFTP(ByVal fileToUpload As String, ByVal FTPHost As String, ByVal FTPUsername As String, ByVal FTPPassword As String, ByVal FTPPassive As Boolean, ByVal subdir As String) As Boolean
Try
If Not FTPHost.EndsWith("/") Then FTPHost += "/"
If Not subdir.EndsWith("/") Then subdir += "/"
Dim request As FtpWebRequest

'create subfolder if requested
If subdir <> String.Empty Then
Try
request =
CType(WebRequest.Create(FTPHost + subdir), FtpWebRequest)
request.Credentials =
New NetworkCredential(FTPUsername, FTPPassword)
request.UsePassive = FTPPassive

request.UseBinary =
True
request.Method = WebRequestMethods.Ftp.MakeDirectory
Dim resp As FtpWebResponse = CType(request.GetResponse(), FtpWebResponse)
Catch ex As Exception
'Folder couldn't be created, or already exists
End Try
End If

'now upload the file
request =
CType(WebRequest.Create(FTPHost + subdir + Path.GetFileName(fileToUpload)), FtpWebRequest)
request.UsePassive = FTPPassive
request.UseBinary =
True
request.Method = WebRequestMethods.Ftp.UploadFile
request.Credentials =
New NetworkCredential(FTPUsername, FTPPassword)

Dim myStreamWriter As Stream = request.GetRequestStream()
Dim contentLen As Integer
Dim buffLength As Integer = 2048
Dim buff(buffLength) As Byte

Dim fi As New FileInfo(fileToUpload)
Dim fs As FileStream = fi.OpenRead()
contentLen = fs.Read(buff, 0, buffLength)
While (contentLen <> 0)
myStreamWriter.Write(buff, 0, contentLen)
contentLen = fs.Read(buff, 0, buffLength)
End While

myStreamWriter.Close()

Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
response.Close()
Return True
Catch ex As Exception
Console.WriteLine("ERROR: FTP Upload FAILED - " + ex.Message)
Return False
End Try
End Function

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.