Monday, October 17, 2011

Upload and Download files from FTP in VB.Net

For Upload and download files from FTP Server you need FTP Detail such as 'FTP Server name', 'User Name' and 'Password'.

First import below namespace in your project

Imports Utilities.FTP

Declare Variables for FTP Detail :

    Dim _HostName As String = "ftp.yourwebsite.com"
    Dim _UserName As String = "yourftpusername"
    Dim _Password As String = "password"
 

Use below function for upload files to FTP :

  Public Sub UploadFileToFTP()
        Dim _FromPath As String
        Dim _ToPath As String
        Dim Dt As New DataTable
        Dim flag As Boolean = False      

        'Create a link to an FtpServer
        Dim ftp As New FTPclient(_HostName, _UserName, _Password)
        Dim _dir As New DirectoryInfo(Application.StartupPath + "\Upload")
      ' Upload multiple files
        For Each _file As FileInfo In _dir.GetFiles("*.*")
            _FromPath = Application.StartupPath + "\Upload\" + _file.Name
            _ToPath = "/UploadedData /" + _file.Name
            'upload a file
            flag = ftp.Upload(_FromPath, _ToPath)
            '' file uploaded then delete

            If flag Then
                _file.Delete()
            End If
        Next
    End Sub


Use below function for Download files from FTP :

Public Sub DownloadXML()
        Try         

            Dim _FromPath As String
            Dim _ToPath As String 
                _FromPath = "/UploadedData /" 

            'Create a link to an FtpServer
            Dim ftp As New FTPclient(_HostName, _UserName, _Password)
            'Get the detailed directory listing of /pub/
            Dim dirList As FTPdirectory = ftp.ListDirectoryDetail(_FromPath)
            'filter out only the files in the list
            Dim filesOnly As FTPdirectory = dirList.GetFiles()
            'download these files
            For Each file As FTPfileInfo In filesOnly
                _ToPath = Application.StartupPath + "\Download\" + file.Filename
                ftp.Download(file, _ToPath, True)
           'Delete file after download
                ftp.FtpDelete(_FromPath + file.Filename)
            Next

        Catch ex As Exception
        End Try

    End Sub


1 comment:

  1. Where can I find the references for Imports Utilities.FTP. my vb.net visual studio 2008 didnt have component for it.

    ReplyDelete