Home » Vb.Net » Uploading Files To FTP in VB.Net

Uploading Files To FTP in VB.Net

In this blog I explored an example to upload files one by one to ftp in Vb.net. The main function is "Upload" and upload function call other functions described in this example. To call "upload" function with if condition use this command:

If Upload(FileNameWithPath, FileNameWithoutPath) = True Then

Imports required for these functions are:

Imports System.Net
Imports System.Net.FtpWebRequest
Imports System.IO
Imports System.Security.Permissions

Modify ftpuser, ftppassword ftphost variable as per your requirement and assign the connection values.


Public Function Upload(ByVal localFilename As String, Optional ByVal targetFilename As String = "") As Boolean
        '1. check source
        If Not File.Exists(localFilename) Then
            Call write_error_log(21006, "file not found.")

        End If
        'copy to FI
        Dim fi As New FileInfo(localFilename)
        Return UploadFile(fi, targetFilename)
    End Function

    Public Function UploadFile(ByVal fi As FileInfo, Optional ByVal targetFilename As String = "") As Boolean
        Dim URI As String = ftphost + targetFilename
        Dim ftp As Net.FtpWebRequest = GetRequest(URI)
        ftp.UseBinary = True
        ftp.Method = Net.WebRequestMethods.Ftp.UploadFile
        ftp.Timeout = 5000
        ftp.UsePassive = False
        ftp.ContentLength = fi.Length
        Const BufferSize As Integer = 2048
        Dim content(BufferSize - 1) As Byte, dataRead As Integer
        Using fs As FileStream = fi.OpenRead()
                'open request to send
                Using rs As Stream = ftp.GetRequestStream
                        dataRead = fs.Read(content, 0, BufferSize)
                        rs.Write(content, 0, dataRead)
                    Loop Until dataRead < BufferSize
                End Using
            Catch ex As Exception
                Call write_error_log(ex.GetHashCode, ex.Message)
                Return False
                'ensure file closed
            End Try
        End Using
        ftp = Nothing
        Return True
    End Function

    Public Function GetRequest(ByVal URI As String) As FtpWebRequest
        'create request
        Dim result As FtpWebRequest = DirectCast(FtpWebRequest.Create(URI), FtpWebRequest)
        result.Credentials = GetCredentials()
        result.KeepAlive = False
        Return result
    End Function

    Public Function GetCredentials() As Net.ICredentials
        Return New Net.NetworkCredential(ftpuser, ftppassword)
    End Function