FTP download txt files

kasteel

Well-known member
Joined
May 29, 2009
Messages
50
Programming Experience
10+
Hi

I am using the code below to download a text file called readme.txt from the httpdocs folder using FTP.

How can I download multiple txt files in the folder without knowing what their names would be? Would appreciate any help.

Here is the code I use to download one file:

VB.NET:
Imports System
Imports System.Net
Imports System.Data
Imports System.IO

Public Class Form1
    Private Sub SimpleButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SimpleButton1.Click

        Const localFile As String = "C:\test1\Readme.txt"
        Const remoteFile As String = "/httpdocs/readme.txt"
        Const host As String = "ftp://yourlinkhere"
        Const username As String = "yourusernamehere"
        Const password As String = "yourpasswordhere"

        Dim URI As String = host & remoteFile
        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

                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
                    responseStream.Close()
                    fs.Flush()
                    fs.Close()
                End Using
                responseStream.Close()
            End Using
            response.Close()
        End Using

    End Sub

End Class
 
I just did something similar to JohnH's advice and it worked fine here. Called ListDirectory to get a list of all the files within the ftp directory. Created a loop for the amount of file returned, within each itteration downloaded the individual file from the ftp.
 
Sure, I'll write up a sample. Do you need to download all the files in the ftp or do you need to filter them and only download specific files? What action are you taking with the files that remain in the ftp directory after downloading them; do you want to delete them from ftp or keep running some type of comparison check to see if you previously downloaded & imported the file(s)?
 
Last edited:
VB.NET:
Private Sub btnDownload_Click(...) Handles btnDownload.Click

        Dim alFtpFiles As New ArrayList
        Dim blnDownloaded As Boolean = False

        'Get a list of the files in the FTP directory
        alFtpFiles = FtpListDirectory(txtURL.Text _
                                      , txtLogin.Text _
                                      , txtPassword.Text)

        'Loop thru each of the items returned
        For Each objFile As Object In alFtpFiles
            'Display purposes
            'lstFiles.Items.Add(objFile.ToString)

            'Download file
            blnDownloaded = FtpDownloadFile(txtURL.Text _
                                            , objFile.ToString _
                                            , txtDownloadDirectory.Text _
                                            , objFile.ToString _
                                            , txtLogin.Text _
                                            , txtPassword.Text)
        Next objFile


End Sub

VB.NET:
'List Ftp Directory Files

Public Function FtpListDirectory(ByVal strUrl As String, ByVal strLogin As String, ByVal strPassword As String) As ArrayList

        Dim alFtpFiles As New ArrayList
        Dim ftpRequest As FtpWebRequest = Nothing
        Dim ftpResponse As FtpWebResponse = Nothing
        Dim strmFiles As StreamReader = Nothing
        Dim strLine As String = ""

        Try
            ftpRequest = CType(WebRequest.Create(strUrl), FtpWebRequest)

            With ftpRequest
                .Credentials = New NetworkCredential(strLogin, strPassword)
                .Method = WebRequestMethods.Ftp.ListDirectory
            End With 
            ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
            strmFiles = New StreamReader(ftpResponse.GetResponseStream)

            If strmFiles IsNot Nothing Then strLine = strmFiles.ReadLine

            While strLine IsNot Nothing
                alFtpFiles.Add(strLine)
                strLine = strmFiles.ReadLine
            End While

        Catch ex As Exception
            Throw ex

        Finally
            If ftpResponse IsNot Nothing Then
                ftpResponse.Close()
                ftpResponse = Nothing
            End If

            If strmFiles IsNot Nothing Then
                strmFiles.Close()
                strmFiles = Nothing
            End If
        End Try

        Return alFtpFiles

    End Function

VB.NET:
Public Function FtpDownloadFile(ByVal strUrl As String, ByVal strFileName As String, ByVal strTargetDirectory As String, ByVal strTargetFileName As String, ByVal strLogin As String, ByVal strPassword As String) As Boolean

        Dim ftpRequest As FtpWebRequest = Nothing
        Dim ftpResponse As FtpWebResponse = Nothing
        Dim strFtpFile As String = ""
        Dim strTargetFile As String = ""
        Dim strmReader As StreamReader = Nothing
        Dim strmResponse As Stream = Nothing
        Dim strmTarget As Stream = Nothing
        Dim strmWriter As StreamWriter = Nothing

        strFtpFile = Path.Combine(strUrl, strFileName)
        strTargetFile = Path.Combine(strTargetDirectory, strTargetFileName)

        Try
            ftpRequest = CType(WebRequest.Create(strFtpFile), FtpWebRequest)

            With ftpRequest
                .Credentials = New NetworkCredential(strLogin, strPassword)
                .UsePassive = False
                .Method = WebRequestMethods.Ftp.DownloadFile
            End With

            ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
            strmTarget = New FileStream(strTargetFile, FileMode.Create)
            strmWriter = New StreamWriter(strmTarget)
            strmResponse = ftpResponse.GetResponseStream()
            strmReader = New StreamReader(strmResponse, System.Text.Encoding.UTF8)
            strmWriter.Write(strmReader.ReadToEnd())

        Catch ex As Exception
            Throw ex

        Finally
            If strmReader IsNot Nothing Then
                strmReader.Close()
                strmReader.Dispose()
            End If

            If strmWriter IsNot Nothing Then
                strmWriter.Close()
                strmWriter.Dispose()
            End If

            If ftpResponse IsNot Nothing Then
                ftpResponse.Close()
                ftpResponse = Nothing
            End If

            If ftpRequest IsNot Nothing Then ftpRequest = Nothing
        End Try

        Return True

    End Function
 
Thanks for the code. I really appreciate it. :)

I want to download only txt files from 1 directory and then delete them on the FTP server after I have downloaded them.
 
Ok just add an If statement into that calling loop of files to parse the file name to get the file extensions, and then only download & delete the files you want. Here is a function for deleting the ftp file afterwards.

VB.NET:
Public Function FtpDeleteFile(ByVal strUrl As String, ByVal strFileName As String, ByVal strLogin As String, ByVal strPassword As String, Optional ByVal blnConfirmPrompt As Boolean = False) As Boolean

        Dim ftpRequest As FtpWebRequest = Nothing
        Dim ftpResponse As FtpWebResponse = Nothing
        Dim strFile As String = ""

        'Delete Confirmation Prompt
        If blnConfirmPrompt = True Then
            Dim dlgResult As DialogResult = Nothing
            Dim strConfirm As String = ""

            strConfirm = String.Format("Delete File : {0}?", strFileName)
            dlgResult = MessageBox.Show(strConfirm, "Delete File", _
                                        MessageBoxButtons.YesNoCancel, _
                                        MessageBoxIcon.Question)
            If dlgResult <> DialogResult.Yes Then Return False
        End If

        Try
            strFile = Path.Combine(strUrl, strFileName)
            ftpRequest = CType(WebRequest.Create(strFile), FtpWebRequest)

            With ftpRequest
                .Credentials = New NetworkCredential(strLogin, strPassword)
                .Method = WebRequestMethods.Ftp.DeleteFile
            End With

            ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse)

        Catch ex As Exception
            Throw ex

        Finally
            If ftpResponse IsNot Nothing Then
                ftpResponse.Close()
                ftpResponse = Nothing
            End If

            If ftpRequest IsNot Nothing Then ftpRequest = Nothing
        End Try

        Return True

    End Function
 
Hi Tom

I ran the code but get an error: "The operation has timed out"

Not sure why. Any tips? :)

Can you give a generic example of what you typed in your txt boxes?
 
Either login problems or there service might have dropped for a moment. And no, im certainly not giving ya FTP & loping/password.... lol

URL: is the full address to the ftp directory you want entry FTP://rootfolder/datafiles
 
he he :) Don't want your passwords and stuff :)

I really appreciate your help.

I get the error message under the FTPDownloadFunction for the following line:

ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
 
Back
Top