Create a GUI for an FTP Client with VB.NET

This Visual Basic Today column builds on the previous column, “Write an FTP Client with VB.NET to Bridge Legacy Software,” which introduced an FTP client with some basic FTP capabilities. It extends that FTP client and begins the implementation of a Windows FTP GUI. I could probably write an entire book on building a Windows FTP application if I elected to cover design, implementation, patterns, GUI design techniques, and testing and deployment issues. However, I don’t have that much time or enough space in this forum.

This column presents an assortment of skills you might need to complete the Windows FTP solution or similar kinds of applications. It further explores the TcpClient namespace and using new controls in Visual Studio .NET 2005. It also demonstrates a couple of patterns that you should know. Although the example it presents is implemented with VS.NET 2005, you could implement it in VS.NET 2003 with simple control substitutions.

Add Get File List to Your FTP Client

Client is one of those words that can be a bit ambiguous. Client can be code that talks to a server, but it also can mean GUI. (A less ambiguous term for GUI client is presentation layer.) This section refers to the client code and not a GUI.

Write an FTP Client with VB.NET to Bridge Legacy Software” began the process of building an FTP client application. It implemented that client as a class library that could be used from any sort of application. Despite being 15 pages long in my word processor, that article still wasn’t long enough to cover implementing all of the commands FTP servers support as defined by RFC (Request For Comment) 959. To make your presentation layer more interesting, implement another command, NLST, which returns a list of files on the FTP server.

To implement NLST, you need to add three more methods to your FtpClient:

  • GetFileList—directly implements the NLST command
  • CreateDataSocket—implements the PASV command and creates a second data socket (The PASV command tells the server to wait for a client to connect to it on a port the server designated.)
  • RequestResponse—returns the actual data that is returned from the server

RequestResponse is useful when you want to retrieve data like a list of files as opposed to server code. Listing 1 shows the implementation of GetFileList, CreateDataSocket, and RequestResponse.

Listing 1: GetFileList, CreateDataSocket, and RequestResponse (to be added to the FtpClient class)

Public Function GetFileList(ByVal mask As String) As String()
Const BUFFER_SIZE As Integer = 512
        Dim buffer(BUFFER_SIZE) As Byte

        Dim socket As Socket = Nothing
        Dim bytes As Integer
        Const separator As Char = "\n"
        Dim messageChunks As String()
        Dim temp As String = ""

        ' Implement this
        socket = CreateDataSocket()
            SendCommand("NLST " + mask)

            While (True)
                Array.Clear(buffer, 0, buffer.Length)
                bytes = socket.Receive(buffer, buffer.Length, 0)
                temp += ASCII.GetString(buffer, 0, bytes)
                If (bytes < buffer.Length) Then Exit While

            End While

            messageChunks = temp.Split(separator)
        End Try

        Return messageChunks
End Function

Private Function CreateDataSocket() As Socket
Dim index1, index2, len, port, partCount As Integer
        Dim ipData, buf, ipAddress As String
        Dim parts(6) As Integer
        Dim ch As Char

        Dim socket As Socket
        Dim ep As IPEndPoint

        Dim reply As String = RequestResponse("PASV")
        index1 = reply.IndexOf("(")
        index2 = reply.IndexOf(")")
        ipData = reply.Substring(index1 + 1, index2 - index1 - 1)
        len = ipData.Length
        partCount = 0
        buf = ""

        Dim I As Integer = 0
        While (I <= len - 1 And partCount <= 6)
            ch = Char.Parse(ipData.Substring(I, 1))
            If (Char.IsDigit(ch)) Then
                buf += ch
            ElseIf (ch <> ",") Then
                Throw New IOException("Malformed PASV reply: " + _
            End If

            If ((ch = ",") Or (I + 1 = len)) Then
                    parts(partCount) = Int32.Parse(buf)
                    partCount += 1
                    buf = ""
                    Throw New IOException("Malformed PASV reply: " _
                                          + reply)
                End Try
            End If
            I += 1
        End While

        ipAddress = String.Format("{0}.{1}.{2}.{3}", parts(0), _
                    parts(1), parts(2), parts(3))

        port = parts(4) << 8
        port = port + parts(5)

        socket = New Socket(AddressFamily.InterNetwork, _
                            SocketType.Stream, ProtocolType.Tcp)
        ep = New IPEndPoint(Dns.Resolve(ipAddress).AddressList(0), _

        Catch ex As Exception
            Throw New IOException("Cannot connect to remote _
                                   server", ex)
        End Try

        Return socket

End Function

Private Function RequestResponse(ByVal command As String) As String
        command += Environment.NewLine
        Dim commandBytes() As Byte = ASCII.GetBytes(command)
        clientSocket.Send(commandBytes, commandBytes.Length, 0)
        Return ReadLine()
End Function

I borrowed these methods from the Microsoft article “How to access a File Transfer Protocol Site by Using Visual Basic .NET,” originally published as knowledge base article 832679 from They are a bit murkier than I like. Code like this often needs some careful refactoring and a couple of attempts in order to “prettify” it, but in this case, that would be a distraction with only cosmetic returns. (For more information on refactoring, refer to Martin Fowler’s book, Refactoring: Improving the Design of Existing Code.)

If you want to learn more about FTP commands, refer to the supported and unsupported FTP commands on the Web site. If you want to learn more about FTP status codes, refer to knowledge base article Q318380, “IIS Status Codes.”

Implement an FTP GUI

Having added the GetFileList, CreateDataSocket, and RequestResponse methods to your FtpClient class (see “Write an FTP Client with VB.NET to Bridge Legacy Software” for the complete listing of the FtpClient), you can now design a presentation layer around the Connect, Login, Disconnect, and GetFileList capabilities of your FtpClient class. You then add a VS.NET 2005 menu, status control, and a user control that can display the files returned from the server.

Add a MenuStrip to the form

The next version of VS.NET replaces the MenuBar with a MenuStrip. The basic functionality is the same, but I find using the MenuStrip a bit clumsier. For example, to add a separator to menus in previous versions of VB, one only had to use the hyphen (-) as the text for the MenuItem. This was exceptionally easy. Whidbey (VS.NET 2005) objectifies as a ToolStripSeparator the indented line that separates regions of a menu. Instead of using a hyphen to create the separator, one needs to right-click over the menu in design mode and select Edit DropDownItems… from the context menu (see Figure 1).

Figure 1: Modifying Menus Is a Bit More Confusing in Whidbey

Selecting the Edit DropDownItems menu opens an Items Collection Editor (see Figure 2) where you can have more precise manipulation of MenuStrip elements. (Beta software is subject to change, so hopefully Microsoft will simplify the MenuStrip behavior.)

Figure 2: Adding a Separator Requires Use and Knowledge of the Items Collection Editor.

MenuStrip behavior—once the menu is created—is similar to MenuBar behavior. Define the StripMenuItem and double-click to generate an event handler. For this article, I added File, View, and Help StripMenuItems. File supports connecting, disconnecting, and exiting. View supports requesting a remote files list, and Help has an About sub-item. For each of these menu items, I created an event handler in the usual way and invoked the related capabilities.

File|Connect invokes the FtpClient.Connect and FtpClient.Login behaviors. File|Disconnect invokes the FtpClient.Disconnect behavior. View|Get Remote Files invokes the FtpClient.GetFileList behavior, and Help|About uses MessageBox.Show (MsgBox) behavior to display a simple About dialog box.

The Form_Load method is used to create an instance of the FtpClient object and a FileListUserControl dynamically. (Find the complete listing for the form at the end of this article.) Whidbey presently separates designer-generated code from user-generated code. It will add designer-generated code to a file named filename.Designer.vb. For example, if you have a form named Form1, Whidbey will create Form1.vb, Form1.Designer.vb, and Form1.resx. Generally, you will add your code to Form1.vb in this scenario.

Create a file list user control

To support listing files on the client and server, you can implement one user control and ultimately use it twice: once for the client-side files and once for the server-side files. In this example, you instantiate one user control for server-side files.

The FileListUserControl is comprised of a Label, a Panel with a Button and ComboBox, and a TreeView. You use the Label to indicate what the control contains. You can ultimately use the Button and ComboBox to change folders or drives where applicable and the TreeView to display the files discovered on the client or the server. For practical purposes, you can surface the Text value of the Label to permit consumers to change it, and hide the ComboBox when the FileListControl represents the remote server and show it when the FileListUserControl represents the client. Figure 3 shows the design-time view of the FileListUserControl.

Figure 3: The FileListUserControl Is a Generic User Control That Accepts a String Array But Is Generally Unaware of the Origin or Meaning of the Data.

The FileListUserControl is straightforward: Pass an array of strings and the SetFiles method calls an Add method for each string in the array, adding the string to the TreeView control. Listing 2 contains the code for the FileListUserControl. (The designer-generated code is contained in a file named *.designer.vb in Whidbey.)

Listing 2: The Implementation of the FileListUserControl

Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Drawing
Imports System.Data
Imports System.IO
Imports System.Windows.Forms

Public Class FileListUserControl

    Public Property Caption() As String
            Return Label1.Text
        End Get
        Set(ByVal value As String)
            Label1.Text = value
        End Set
    End Property

    Public Sub SetFiles(ByVal files() As String)

        Dim file As String
        For Each file In files
            If (file.Trim() <> String.Empty) Then
            End If
    End Sub

    Private Sub Add(ByVal file As String)
        Broadcaster.Broadcast(String.Format("Adding {0}", file))
        treeViewFiles.Nodes.Add(New TreeNode(file))
    End Sub

    Private Sub FileListUserControl_Resize(ByVal sender _
    As System.Object, _
    ByVal e As System.EventArgs) Handles MyBase.Resize
        treeViewFiles.SetBounds(0, 80, Width, Height - 80)
        Label1.SetBounds(0, 0, Width, 40)
        Panel1.SetBounds(0, 40, Width, 40)
    End Sub
End Class

More by Author

Must Read