Total Visual SourceBook

Total Visual SourceBook CD and Printed Manual

Microsoft Access/ Office 2016, 2013, 2010, and 2007 Version
is Shipping!

New features in Total Visual SourceBook for Access, Office 2007 and VB6

Supports Access/Office 2016, 2013, 2010 and 2007, and Visual Basic 6.0!

Separate version for Access/Office 2003, 2002, and 2000.

Separate version for:
Access 97/95


View all FMS products for Microsoft AccessAll Our Microsoft Access Products

SourceBook Info:

Why SourceBook?

 

"The code is exactly how I would like to write code and the algorithms used are very efficient and well-documented."

Van T. Dinh, Microsoft MVP

 

 

 

Microsoft Access, Office/VBA, VB6 Modules royalty-free source code libraryMicrosoft Access Modules royalty-free source code libraryMicrosoft Access VBA and VB6 Module Library Free trial of Total Visual SourceBook for Microsoft Access, Office, VB6 and VBA

Class: InternetFTP in Category Internet/Web : HTTP/FTP from Total Visual SourceBook

Use File Transfer Protocol (FTP) standards to open connections and sessions on a remote FTP site, download (get) files, create directories, upload (put) files, delete and rename files and directories.

Includes support for VB6 and VBA with 32 and 64 bit API calls. This class works directly through the WININET.DLL library which exists if Internet Explorer is installed and does not need to be a library reference. This means you can distribute simple FTP functionality with your application with little overhead.

Procedure List

Procedure Name

Type

Description

(Declarations) Declarations Declarations and private variables for the CInternetFTP class
ConnectionHandle Property Get the handle to the Internet connection. After establishing a session to WININET.DLL with the OpenSession() method, you connect to an FTP server with the Connect() method. Once this call has been made, and returned successfully, this property is the connection handle value returned to the class by the WININET.DLL resource.
CurrentDirectory Property Get the current directory (folder) as set on the FTP server. This property is read-only. To change the directory on the FTP server, use the SetCurrentDirectory method.
Password Property Get the current login password Many FTP servers support anonymous logins. This means that you can log into the server as a guest without having a pre-defined account or password. If you are accessing an FTP server that requires an existing user account and password, set this property to your password before calling the Connect() method. If you do not specify a value for this property, a blank password is used, allowing access to anonymous FTP servers.
ProxyString Property Get the proxy server. If you attempt to connect to an FTP site through a proxy server, set this property before calling the OpenSession() method. Set this property to the name of the proxy server (or servers) to use. If you do not specify a value for this property, the OpenSession() method opens the Internet session without any proxy server information. The Win32 Internet functions only recognize CERN type proxies (HTTP only) and the TIS FTP gateway (FTP only). The Win32 Internet functions also support SOCKS proxies. FTP and Gopher requests can be made through a CERN type proxy either by changing them to an HTTP request or by using the WININET.DLL InternetOpenUrl() function.
Server Property Get the URL of the FTP server. Before performing FTP operations, you must specify the URL of the FTP site you want to connect to. Set this property to a valid FTP URL, such as ftp.microsoft.com before calling Connect() method.
SessionActive Property Determine if there is an active session open to an FTP site. This value is True if the OpenSession() method has been called successfully. You can check this property to ensure a session is active before performing subsequent FTP operations.
SessionHandle Property Get the handle to the Internet session. Before performing any FTP operations, you must establish a session to the WININET.DLL resource. Call the OpenSession() method to do this. Once this call has been made, and returned successfully, this property is the handle value returned to the class by the WININET.DLL resource.
TransferType Property Get the current TransferType setting. This property tells the class whether to do ASCII or Binary transfers for subsequent calls to the GetFile() and PutFile() methods. Set this value according to the EnumFTPTransferType enumerated type.
UserName Property Get the name of the user. Many FTP servers support anonymous logins. This means that you can log into the server as a guest without having a pre-defined account or password. If you are accessing an FTP site that requires an existing user account, set this property to your user name before calling the Connect() method. If you do not specify a value for this property, the default user name of "anonymous" is used, allowing access to anonymous FTP servers.
Class_Initialize Initialize Initialize values to defaults which may be overridden with property settings and methods
Class_Terminate Terminate Clean up class when it closes
CloseSession Method Close the current handles to the Internet. Call this method when you are finished using the FTP class.
DirectoryFileName Method Get the directory (folder) or file name for the current directory's item based on how LoadDirectoryFiles was called
FileSize Method Get the file size of the specified item in the current directory (directories do not return a file size).
DirectoryFileAttribute Method Get the directory (folder) or file attributes value of the specified item in the current directory.
DirectoryFileAttributeString Method Get the directory (folder) or file attributes of the specified item in the current directory as a readable string.
DirectoryFileCount Method Get the count of objects in the current directory based on how LoadDirectoryFiles was called with a mask. Use GetDirectoryFiles to get the individual directory folder and file names.
LastDLLError Method Get the last error raised by a call to a DLL function. This class saves the VBA/VB6 Err.LastDLLError value after every call to the WININET.DLL resource. This means that error information can be retrieved by using this property without having to directly access the VBA/VB6 Err object.
Connect Method Connect to the named FTP server. The server name, user name, and password properties must be set to a valid FTP server before calling this method.
RefreshFileList Private Refresh the file list for the current folder on the FTP server. Resets the connection if necessary. Uses the previously specified login information.
Reconnect Private Reconnect to the FTP server with the previously specified login information and stay in the same folder.
ConnectLogin Method Connect to the named FTP server with the login information. An alternative to assigning each property and using the Connect function.
CreateDirectory Method Create a directory in the current folder of the FTP site. You must have sufficient permissions on the FTP server to create (make) a directory. Most anonymous FTP connections do not allow the creation or deletion of directories. Check the class LastDLLError property for information on failure results of this method.
Disconnect Method Disconnects the link to the server. Call this method to disconnect from an FTP server that was connected by the Connect() method. If there is no active server connection, this method fails silently.
GetFilesAll Method Download (retrieve or import) all the files (not directories) from the remote server's current folder to a folder in the local drive. To change the current FTP directory, use SetCurrentDirectory before calling this. If the local file exists, it is overwritten. In order to retrieve a file, your FTP login account must have read permission for the file.
GetFile Method Download (retrieve or import) the specified file from the remote server to your local drive. The remote file name is relative to the current FTP directory. To change the current directory, use SetCurrentDirectory. If the local file exists, it is overwritten. In order to retrieve a file, your FTP login account must have read permission for the file.
GetFTPFileName Private Extract the name part of a fully qualified FTP file name. This function differs from other path parsing functions since it uses the forward slash (/) character for path delimiting. This is because FTP sites work with the UNIX standard for paths.
GetFTPPath Method Extract the directory (folder) part of a fully qualified FTP file name. This function differs from other path parsing functions since it uses the forward slash (/) character for path delimiting. This is because FTP sites work with the UNIX standard for paths.
OpenSession Method Open a session to the Internet resource. Before accessing Internet functionality through the WININET.DLL resource, you must open a session to it. Do this by calling the OpenSession() method. This method establishes a session to the DLL and obtains a handle to be used for subsequent operations.
PutFile Method Upload (post) a local file to the remote FTP server. You must have the appropriate permissions on the FTP server for the directory you are trying to write to.
IsLocalFile Private Determine if a file name exists on the local disk (not FTP server)
RenameDirectoryFile Method Rename a directory (folder) or file on the remote FTP server. Name may be a partially or fully qualified directory or file name relative to the current directory. To change the current directory, use SetCurrentDirectory. You must have the appropriate permissions on the FTP server for the directory and/or file being renamed.
DeleteDirectoryFiles Method Delete all the files matching the file mask in an FTP server directory (folder) relative to the current folder as defined by SetCurrentDirectory. The directory and subdirectories are not deleted.
DeleteDirectory Method Delete all the files in a directory (folder) and the directory on the remote FTP server relative to the current folder as defined by SetCurrentDirectory. If there are subdirectories, the subdirectories are not deleted and the folder cannot be deleted. To delete a directory and all its contents, use the DeleteDirectoryAll function instead.
DeleteDirectoryAll Method Delete an FTP directory and all the files and subfolders in the directory relative to the current folder as defined by SetCurrentDirectory. This is a recursive procedure that is called for each subfolder that's found until all the subfolders and their files are deleted.
DeleteFile Method Delete a file on the remote FTP server relative to the current folder as defined by SetCurrentDirectory. You must have the appropriate permissions on the FTP server to delete the file, otherwise it may trigger an "550 Access is denied" error message.
SetCurrentDirectory Method Change the directory folder on the remote FTP server with options to refresh the list of files.
ClearDLLError Private Clears the class's last DLL error
DirectoryExists Method Determine if a directory (folder) exists in the current directory. To change the current directory, use SetCurrentDirectory before calling this.
FileExists Method Determine if a file exists in the current directory (folder). To change the current directory, use SetCurrentDirectory before calling this.
IsDirectoryAttribute Private Determine from a file's attribute whether it's a directory (folder)
DirectoryFileExists Private Determine if a directory (folder) or file exists in the current directory. To change the current directory, use SetCurrentDirectory before calling this.
LoadDirectoryFiles Method Assign the module level array of file information for the current directory folder. To change the current directory, use SetCurrentDirectory.
GetDirectoryFiles Method Get the list of files in the current directory folder. Run LoadDirectoryFiles before this procedure so that matypFileInfo() is initialized.
GetDirectoryFileSizes Method Get the list of files and file sizes in the current folder (folders are not included. Run LoadDirectoryFiles before this procedure so that matypFileInfo() is initialized.
SaveDLLError Private Set the class Last DLL error properties
GetErrorDescription Private Translate error number to error string description
GetEnglishAttributes Private Get a human readable version of an FTP directory entry
TrimNull Private Return the passed string terminated at the first null character. If there isn't a null, the entire string is returned.
StripServerName Private Delete the server name from a file name if it exists (e.g. "ftp.domain.com/folder/filename" becomes "/folder/filename")

Example Code for Using Class: InternetFTP

' Commments: Examples of using the CInternetFTP class to use File Transfer Protocol (FTP) standards to connect, view, upload and download files with a remote FTP site.
'            To use these examples, set the constants in this section to values that work with your FTP site.
'            These procedures are available:
'            - Example_CInternetFTP_ViewFiles         View files in your FTP folders (does not make any changes)
'            - Example_CInternetFTP_DownloadFiles     Download all files and one file from an FTP folder into a local folder
'            - Example_CInternetFTP_UploadFiles       Upload files from your local drive to the FTP folder; create and rename directories and files on the FTP Server

' To use these examples, create a new module and paste this code into it.
' Then run any of the procedures by putting the cursor in the procedure and pressing:
'    F5 to run it, or
'    F8 to step through it line-by-line (see the Debug menu for more options)

' This example uses the old Microsoft FTP site which can change at any time. This site, is of course, ReadOnly for anonymous login.
' Change these with your FTP server login values with write permissions to run the examples that upload files and create/rename/delete directories and files on the server.
Private Const mcstrServer As String = "ftp.microsoft.com"
Private Const mcstrUserName As String = "anonymous"
Private Const mcstrPassword As String = ""

' Specify a folder and file name in that folder (that file and all files of that folder are downloaded in the example)
Private Const mcstrFTPFolder As String = "deskapps/word"
Private Const mcstrRemoteFile As String = "readme.txt"

' Folder on FTP Server to create and upload files to
Private Const mcstrFTPUploadFolder As String = "test-uploads"
' Subfolder to create in the upload folder
Private Const mcstrFTPUploadSubFolder As String = "subfolder"

' Local folder to store the downloaded files
Private Const mcstrLocalFolder As String = "C:\Total Visual SourceBook 2013\Samples\"
Private Const mcstrLocalFolderFTP As String = mcstrLocalFolder & "FTP\"
Private Const mcstrLocalFile As String = "sample.txt"

Private Sub Example_CInternetFTP_ViewFiles()
  ' Commments: Examples of using the CInternetFTP class to use File Transfer Protocol (FTP) standards to get set connections, sessions, and retrieve file information from a remote FTP site.
  '            Includes support for VB6 and VBA with 32 and 64 bit API calls.

  Const cstrMask As String = "*.*"
  Dim clsInternetFTP As CInternetFTP
  Dim lngFiles As Long

  ' Initialize FTP class
  Set clsInternetFTP = New CInternetFTP

  ' Open the Internet DLL
  If clsInternetFTP.OpenSession() Then
    ' Session successfully opened

    ' Set class login properties
    clsInternetFTP.Server = mcstrServer
    clsInternetFTP.UserName = mcstrUserName
    clsInternetFTP.Password = mcstrPassword

    ' Make the connection
    If clsInternetFTP.Connect() Then
      ' Successfully connected

      ' Initialize retrieval of folders and files in the current directory (folder)
      lngFiles = clsInternetFTP.LoadDirectoryFiles(cstrMask)
      If lngFiles > 0 Then
        Call Example_CInternetFTP_DirectoryFiles(clsInternetFTP)
      End If

      ' Change to a subfolder
      If clsInternetFTP.SetCurrentDirectory(mcstrFTPFolder, True, cstrMask) Then
        Debug.Print
        Debug.Print "Subfolder: " & mcstrFTPFolder
        Call Example_CInternetFTP_DirectoryFiles(clsInternetFTP)
      Else
        MsgBox "Directory could not be changed:" & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
      End If

    Else
      MsgBox "Connection failed:" & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
    End If

  Else
    MsgBox "Could not open Internet session", vbCritical
  End If

  ' Clean up
  Set clsInternetFTP = Nothing
End Sub

Private Sub Example_CInternetFTP_DirectoryFiles(clsInternetFTP As CInternetFTP)
  ' Comments: Example of showing the list of directories (folders) and files of the current directory in the Immediate Window
  ' Params  : clsInternetFTP        Internet FTP class already initialized to the current directory (folder)

  Dim lngFolders As Long
  Dim astrFolderNames() As String
  Dim lngCounter As Long
  Dim lngFiles As Long
  Dim astrFileNames() As String
  Dim adblFileSizes() As Double

  ' Get the folders in the current directory:
  Debug.Print "Folders in directory: " & clsInternetFTP.DirectoryFileCount(True, False)
  lngFolders = clsInternetFTP.GetDirectoryFiles(True, False, astrFolderNames())
  For lngCounter = 1 To lngFolders
    Debug.Print lngCounter, "<" & astrFolderNames(lngCounter) & ">"
  Next lngCounter

  ' Get the files in the current directory:
  Debug.Print
  Debug.Print "Files in directory: " & clsInternetFTP.DirectoryFileCount(False, True)
  lngFiles = clsInternetFTP.GetDirectoryFileSizes(astrFileNames(), adblFileSizes(), "K")
  For lngCounter = 1 To lngFiles
    ' Display file size and name
    Debug.Print lngCounter, Format$(adblFileSizes(lngCounter), "Standard") & " K", astrFileNames(lngCounter)
  Next lngCounter

End Sub

Private Sub Example_CInternetFTP_DownloadFiles()
  ' Commments: Examples of using the CInternetFTP class to use File Transfer Protocol (FTP) standards to download (import) files from an FTP site.
  '            Includes support for VB6 and VBA with 32 and 64 bit API calls.

  Dim clsInternetFTP As CInternetFTP
  Dim strRemoteFile As String
  Dim strLocalFileNew As String
  Dim fOK As Boolean
  Dim lngDownloads As Long

  ' Initialize FTP class
  Set clsInternetFTP = New CInternetFTP

  ' Open the Internet DLL
  If clsInternetFTP.OpenSession() Then
    ' Session successfully opened, so pass credentials to login
    If clsInternetFTP.ConnectLogin(mcstrServer, mcstrUserName, mcstrPassword) Then
      ' Set the current folder
      If clsInternetFTP.SetCurrentDirectory(mcstrFTPFolder, False) Then

        ' Download all the FTP files from that folder into a local folder
        lngDownloads = clsInternetFTP.GetFilesAll(mcstrLocalFolderFTP, "*.*")
        MsgBox lngDownloads & " files downloaded from " & mcstrFTPFolder & " to the local folder " & mcstrLocalFolderFTP

        strRemoteFile = mcstrServer & "/" & mcstrFTPFolder & "/" & mcstrRemoteFile
        strLocalFileNew = mcstrLocalFolderFTP & mcstrRemoteFile
        If MsgBox("Do you want to download " & strRemoteFile & " to " & strLocalFileNew & "?", vbQuestion + vbYesNo) = vbYes Then
          ' Download one file
          fOK = clsInternetFTP.GetFile(strRemoteFile, strLocalFileNew)
          If fOK Then
            MsgBox strLocalFileNew & " created from " & strRemoteFile
          Else
            MsgBox strLocalFileNew & " failed to be created from " & strRemoteFile & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
          End If
        End If
      End If
    End If
  Else
    MsgBox "Could not open Internet session"
  End If

  ' Clean up
  Set clsInternetFTP = Nothing

End Sub

Private Sub Example_CInternetFTP_UploadFiles()
  ' Commments: Examples of using the CInternetFTP class to use File Transfer Protocol (FTP) standards to create, rename, and delete directories and files, and upload files to an FTP site.
  '            Includes support for VB6 and VBA with 32 and 64 bit API calls.
  '            This example is best used if you can step through the procdure calls and observe the contents of the FTP folders separately.

  Const cstrRemoteFile As String = "RemoteName.txt"
  Const cstrRenamedFile As String = "renamed.txt"
  Dim clsInternetFTP As CInternetFTP
  Dim strRemoteDirNew As String
  Dim strRemoteFileNew As String
  Dim strLocalFile As String
  Dim strTempName As String
  Dim fOK As Boolean

  ' Initialize FTP class
  Set clsInternetFTP = New CInternetFTP

  ' Open the Internet DLL
  If clsInternetFTP.OpenSession() Then
    ' Session successfully opened, so pass credentials to login
    If clsInternetFTP.ConnectLogin(mcstrServer, mcstrUserName, mcstrPassword) Then

      ' Change to a subfolder
      If clsInternetFTP.SetCurrentDirectory(mcstrFTPFolder, False) Then

        ' Create new subfolder
        If clsInternetFTP.CreateDirectory(mcstrFTPUploadFolder) Then

          ' Change the current directory to the new directory but don't load the list of files in it
          fOK = clsInternetFTP.SetCurrentDirectory(mcstrFTPUploadFolder, False)

          If fOK Then
            ' Examples of creating, renaming and deleting folders
            ' Create another subfolder
            fOK = clsInternetFTP.CreateDirectory(mcstrFTPUploadSubFolder)

            If fOK Then
              ' Rename the folder
              strTempName = mcstrFTPUploadSubFolder & "_Renamed"
              If clsInternetFTP.RenameDirectoryFile(mcstrFTPUploadSubFolder, strTempName) Then

                ' Create the subfolder again since we use it later
                fOK = clsInternetFTP.CreateDirectory(mcstrFTPUploadSubFolder)

                ' Delete the renamed folder
                If Not clsInternetFTP.DeleteDirectory(strTempName) Then
                  ' For the example, not being able to delete this folder is okay because it's not used later
                  MsgBox strTempName & " folder could not be deleted" & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
                End If
              Else
                MsgBox mcstrFTPUploadSubFolder & " could not be renamed to " & strTempName & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
              End If
            Else
              MsgBox mcstrFTPUploadSubFolder & " could not be created." & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
            End If

            If fOK Then
              ' The local file to upload
              strLocalFile = mcstrLocalFolder & mcstrLocalFile

              ' FTP Folder to upload the file
              strRemoteDirNew = mcstrServer & "/" & mcstrFTPFolder & "/" & mcstrFTPUploadFolder
              strRemoteFileNew = strRemoteDirNew & "/" & cstrRemoteFile

              ' Upload a file; the folder where the file is uploaded becomes the current folder
              fOK = clsInternetFTP.PutFile(strLocalFile, strRemoteFileNew)

              If fOK Then
                If MsgBox("Do you want to rename the file " & strRemoteFileNew & "?", vbQuestion + vbYesNo) = vbYes Then

                  ' Rename a file
                  fOK = clsInternetFTP.RenameDirectoryFile(cstrRemoteFile, cstrRenamedFile)

                  If fOK Then
                    ' Rename file into a subfolder
                    strRemoteFileNew = mcstrFTPUploadSubFolder & "/" & cstrRenamedFile
                    fOK = clsInternetFTP.RenameDirectoryFile(cstrRenamedFile, strRemoteFileNew)
                  End If

                  If fOK Then
                    If MsgBox("Do you want to delete the " & strRemoteFileNew & " file?", vbQuestion + vbYesNo) = vbYes Then
                      ' Delete a file; the folder where the file is deleted becomes the current folder
                      fOK = clsInternetFTP.DeleteFile(strRemoteFileNew)
                      If fOK Then
                        MsgBox strRemoteFileNew & " deleted"
                      Else
                        MsgBox strRemoteFileNew & " could not be deleted" & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
                      End If
                    End If
                  Else
                    MsgBox cstrRemoteFile & " failed to be renamed to " & cstrRenamedFile & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
                  End If
                End If
              Else
                MsgBox strRemoteFileNew & " failed to be created from " & strLocalFile & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
              End If
            End If
          Else
            MsgBox mcstrFTPUploadFolder & " could not be created." & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
          End If
        Else
          MsgBox mcstrFTPUploadFolder & " could not be created." & vbCrLf & clsInternetFTP.LastDLLError, vbCritical
        End If
      End If
    End If
  Else
    MsgBox "Could not open Internet session", vbCritical
  End If

  ' Clean up
  Set clsInternetFTP = Nothing

End Sub

Microsoft Access Module LibraryOverview of Total Visual SourceBook

The source code in Total Visual SourceBook includes modules and classes for Microsoft Access, Visual Basic 6 (VB6), and Visual Basic for Applications (VBA) developers. Easily add this professionally written, tested, and documented royalty-free code into your applications to simplify your application development efforts.

Additional Resources