Below is a code snippet of a function that allows you to download an FTP file using VB.net. Along the same theme as the earlier post on listing files on a FTP site, the function uses a FTPWebRequest and FTPWebResponse from the System.Net namespace.
The function takes the following parameters,
- ftpAddress – this is the remote server address in the format FTP://server/foldername
- ftpUser – this is the user name with access to the FTP server
- ftpPassword – password for the ftpUser
- fileToDownload – file name you want to download from the FTP folder
- downloadTargetFolder – local folder to download file to
- deleteAfterDownload – boolean value to set if you would like to delete the file on the FTP site after download
- ExceptionInfo – if an exception occurs then the error is passed back by reference through this parameter
The function will return a true or false to signify if the file has been downloaded successfully.
''' Shared method which will download a single file to a target location Public Shared Function DownloadSingleFile(ftpAddress As String, _ ftpUser As String, _ ftpPassword As String, _ fileToDownload As String, _ downloadTargetFolder As String, _ deleteAfterDownload As Boolean, _ ExceptionInfo As Exception) As Boolean Dim FileDownloaded As Boolean = False Try Dim sFtpFile As String = ftpAddress & fileToDownload Dim sTargetFileName = System.IO.Path.GetFileName(sFtpFile) sTargetFileName = sTargetFileName.Replace("/", "\") sTargetFileName = downloadTargetFolder & sTargetFileName My.Computer.Network.DownloadFile(sFtpFile, sTargetFileName, ftpUser, ftpPassword) If deleteAfterDownload Then Dim ftpRequest As FtpWebRequest = Nothing ftpRequest = CType(WebRequest.Create(sFtpFile), FtpWebRequest) With ftpRequest .Credentials = New NetworkCredential(ftpUser, ftpPassword) .Method = WebRequestMethods.Ftp.DeleteFile End With Dim response As FtpWebResponse = CType(ftpRequest.GetResponse(), FtpWebResponse) response.Close() ftpRequest = Nothing FileDownloaded = True End If Catch ex As Exception ExceptionInfo = ex End Try Return FileDownloaded End Function