File Transfer Protocol Connections  
 

To establish a connection using the FTP control, you should call the Connect method and check the return value to ensure that the connection was successful. This can be done one of several ways, and which approach you use largely depends on personal preference and the structure of your program.

Method Arguments

You can call the Connect method with a number of different arguments, all of which are optional. The most common use would look like this:

Dim nError As Long

nError = FtpClient1.Connect(strHostName, ftpPortDefault, strUserName, strPassword)
If nError > 0 Then
    MsgBox FtpClient1.LastErrorString, vbExclamation
    Exit Sub
End If

In this example, the strHostName string variable contains the name of the server to connect to, the strUserName variable contains the username and the strPassword variable contains the password used to authenticate that user. If the function returns a value other than zero, this indicates an error and a message box is used to display the error to the user.

Property Values

Another method is to set the host name, user name and password using the control's properties and then calling the Connect method without any arguments. Here is an example of how that could be done:

Dim nError As Long

FtpClient1.HostName = "ftp.microsoft.com"
FtpClient1.UserName = "anonymous"
FtpClient1.Password = "user@domain"

nError = FtpClient1.Connect()
If nError > 0 Then
    MsgBox FtpClient1.LastErrorString, vbExclamation
    Exit Sub
End If

Note that the RemotePort property is not specified, which means that the default port number should be used. As with the previous example, if the connection fails then the method will return an error code and a message box is displayed to the user.

Uniform Resource Locators

A third approach is to specify a URL by setting the URL property and then calling the Connect method without any arguments. By setting the URL property, the control will automatically update the various related properties such as HostName and RemotePort. Here is an example of how this could be done:

Dim nError As Long

FtpClient1.URL = "ftp://ftp.microsoft.com/"

nError = FtpClient1.Connect()
If nError > 0 Then
    MsgBox FtpClient1.LastErrorString, vbExclamation
    Exit Sub
End If

If you prefer to use URLs, this approach provides the simplest means of establishing the connection. It should be noted that if the URL property is assigned an invalid value, then the control will throw an exception. If you are using URLs provided by a user, it is strongly recommended that you implement an error handler, otherwise your program may terminate if the user specifies an incorrect or incomplete URL.