Visual Basic .NET Forums  
Click here to advertise with us

Go Back   Visual Basic .NET Forums > Components & Controls > Net / Sockets

Net / Sockets Components for network and related use

VB.NET Forums Newsletter Signup:
Email address:


Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 09-16-2009, 5:43 AM
VB.NET Forum Enthusiast
.NET Framework: .NET 2.0 (VS 2005)
 
Join Date: May 2009
Posts: 35
Reputation: 12
kasteel is on a distinguished programming path ahead
Question FTP download txt files

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:

Code:
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
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 09-16-2009, 6:48 AM
JohnH's Avatar
VB.NET Forum Moderator
.NET Framework: .NET 3.5 (VS 2008)
 
Join Date: Dec 2005
Location: Norway
Age: 37
Posts: 10,322
Reputation: 1315
JohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond reputeJohnH has a reputation beyond repute
Default

FtpWebRequest.Method Property (System.Net)
For example use the ListDirectory or ListDirectoryDetails ftp method.
__________________
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 09-17-2009, 7:43 AM
VB.NET Forum Enthusiast
.NET Framework: .NET 2.0 (VS 2005)
 
Join Date: May 2009
Posts: 35
Reputation: 12
kasteel is on a distinguished programming path ahead
Default

Hi

Thanks for the response but I have already tried that. No luck.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 09-17-2009, 8:25 AM
Tom Tom is offline
VB.NET Forum Idol
.NET Framework: .NET 3.5 (VS 2008)
 
Join Date: Aug 2005
Posts: 711
Reputation: 335
Tom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NET
Default

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.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 09-17-2009, 6:04 PM
VB.NET Forum Enthusiast
.NET Framework: .NET 2.0 (VS 2005)
 
Join Date: May 2009
Posts: 35
Reputation: 12
kasteel is on a distinguished programming path ahead
Default

Hi Tom

Do you mind showing me what you did?

Thanks
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 09-17-2009, 6:14 PM
Tom Tom is offline
VB.NET Forum Idol
.NET Framework: .NET 3.5 (VS 2008)
 
Join Date: Aug 2005
Posts: 711
Reputation: 335
Tom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NET
Default

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 by Tom; 09-17-2009 at 6:30 PM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 09-17-2009, 7:26 PM
Tom Tom is offline
VB.NET Forum Idol
.NET Framework: .NET 3.5 (VS 2008)
 
Join Date: Aug 2005
Posts: 711
Reputation: 335
Tom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NET
Default

Code:
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
Code:
'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
Code:
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
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 09-17-2009, 7:53 PM
VB.NET Forum Enthusiast
.NET Framework: .NET 2.0 (VS 2005)
 
Join Date: May 2009
Posts: 35
Reputation: 12
kasteel is on a distinguished programming path ahead
Default

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.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 09-17-2009, 9:58 PM
Tom Tom is offline
VB.NET Forum Idol
.NET Framework: .NET 3.5 (VS 2008)
 
Join Date: Aug 2005
Posts: 711
Reputation: 335
Tom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NETTom master of VB.NET
Default

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.

Code:
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
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 09-18-2009, 6:29 AM
VB.NET Forum Enthusiast
.NET Framework: .NET 2.0 (VS 2005)
 
Join Date: May 2009
Posts: 35
Reputation: 12
kasteel is on a distinguished programming path ahead
Default

Thanks Tom

I really appreciate your help.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply

Bookmarks


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On





All times are GMT -4. The time now is 2:22 AM.

Powered by vBulletin® Version 3.8.5
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2


For advertising opportunities click here.