FTP download file code Review

Posted on 2008-11-16
Last Modified: 2013-11-13
I am using an example from a Networking Programming book called: "Network Programming in .NET" by Fiach Reid.

The code works perfectly uploading file to a FTP site but it does not work when downloading. I dont get any error messages, the program simply hangs and stops responding after the download button is clicked.

Help is appreciated on this issue.

I am attaching a code snipet for reference.

Thank you
Private Sub cmdDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDownload.Click

        Dim filedata As Byte()


        filedata = sendPassiveFTPcmd("RETR " + lstFiles.SelectedItem.ToString() + vbCrLf)

        Dim fs As FileStream = New FileStream(SaveFileDialog1.FileName, FileMode.CreateNew)

        fs.Write(filedata, 0, filedata.Length)


   End Sub

Public Function sendPassiveFTPcmd(ByVal cmd As String) As Byte()

        Dim szData() As Byte

        Dim al As New System.Collections.ArrayList

        Dim bytes As Int32

        Dim RecvBytes(Byte.MaxValue) As Byte

        szData = System.Text.Encoding.ASCII.GetBytes(cmd.ToCharArray())

        Dim totalLenght As Int32 = 0

        Dim PassiveConnection As NetworkStream

        PassiveConnection = createPassiveConnection()

        txtStatus.Text += vbCrLf + "Sent: " + cmd

        Dim commandStream As StreamReader = New StreamReader(NetStrm)

        NetStrm.Write(szData, 0, szData.Length)

        Do While (True)

            bytes = PassiveConnection.Read(RecvBytes, 0, RecvBytes.Length)

            If bytes <= 0 Then Exit Do

            totalLenght += bytes



        al = al.GetRange(0, totalLenght)

        txtStatus.Text += vbCrLf + "Rcvd:" + commandStream.ReadLine() '125

        txtStatus.Text += vbCrLf + "Rcvd:" + commandStream.ReadLine()

        Return CType(al.ToArray((New Byte).GetType()), Byte())

    End Function

Open in new window

Question by:virgilar
    LVL 19

    Expert Comment

    Where does the code hang?

    Author Comment


    The filedata variable never gets populated. Although, the function SendPassiveFTPcmd seems to work fine (since it does not error out), it never returns a value to populate the filedata variable.

    filedata = sendPassiveFTPcmd("RETR " + lstFiles.SelectedItem.ToString() + vbCrLf)

    I believe that the problem is on the return statement. Thats supposed to return the bytes back to the variable on the download_click routine.

    Return CType(al.ToArray((New Byte).GetType()), Byte())


    Accepted Solution

    I found out what the problem is:

    If you take a look at the picture attached the file name includes the date, time and size on the string. I hard coded a file name in the code and ran the download and everything worked fine.

    So my problem is that i have to display the file names only on my list box instead. I have to trim the file name some how. The code below show how i add the file name to the list box.

    The previous code i had included on my message works fine. The problem lies on how the string containing the file name is read by the download routine.

    Public Sub GetRemoteFolders()
            Dim FilesandFolders() As String
            Dim FileorFolder As String
            Dim FolderList As String = ""
            Dim lastSpace As Integer = 0
            FolderList = Encoding.ASCII.GetString(sendPassiveFTPcmd("List" + vbCrLf))
            FilesandFolders = FolderList.Split(vbCr.ToCharArray())
            Dim i As Integer
            For i = 0 To FilesandFolders.GetUpperBound(0) - 1
                If FilesandFolders(i).StartsWith("-") Or FilesandFolders(i).StartsWith("d") Then
                    lastSpace = 59 ' Unix Format
                    lastSpace = 39 ' Dos Format
                End If
                FileorFolder = FilesandFolders(i).Substring(lastSpace)
                If FileorFolder.IndexOf(".") <> -1 Then
                End If
        End Sub

    Open in new window

    LVL 19

    Expert Comment

    As I look at it again, the problem is more likely in the ReadLine of the commandStream.  I don't know the FTP spec i nthat detail.  Is it stuck waiting for the command response?

    That woudl seem to be the most likely thing if it's hung, as you initially describe.  You can put a breakpoint on the return statement and see the state of things at that point.  If it never gets there, you can break and see which line it's on.
    LVL 19

    Expert Comment

    Sorry, I'm watching football here and didn't see that you had already posted the solution.

    Author Comment

    No problem. I am doing the same here. LOL.  Thanks for your help on this.

    I will do some research and try to find out how to display the file name only. That should be it.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Navigation is an important part of web design from a usability perspective. But it is often a pain when it comes to a developer’s perspective. By navigation, it often means menuing. This is less theory and more practical of how to get a specific gro…
    Having just graduated from college and entered the workforce, I don’t find myself always using the tools and programs I grew accustomed to over the past four years. However, there is one program I continually find myself reverting back to…R.   So …
    The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
    This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now