Listing files on an FTP server

by Richard Russell, April 2013

The code below list the files on an FTP server.

        FTP_PORT = 21 : REM default for FTP servers
        _INTERNET_SERVICE_FTP = 1
        OPEN_TYPE_PRECONFIG = 0 : REM use registry configuration
        OPEN_TYPE_DIRECT = 1 : REM direct to net
        OPEN_TYPE_PROXY = 3 : REM via named proxy
        OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY = 4 : REM prevent using Java
 
        SYS "LoadLibrary", "WININET.DLL" TO wininet%
        SYS "GetProcAddress", wininet%, "InternetOpenA"           TO `InternetOpen`
        SYS "GetProcAddress", wininet%, "InternetConnectA"        TO `InternetConnect`
        SYS "GetProcAddress", wininet%, "FtpSetCurrentDirectoryA" TO `FtpSetCurrentDirectory`
        SYS "GetProcAddress", wininet%, "FtpFindFirstFileA"       TO `FtpFindFirstFile`
        SYS "GetProcAddress", wininet%, "InternetFindNextFileA"   TO `InternetFindNextFile`
        SYS "GetProcAddress", wininet%, "InternetCloseHandle"     TO `InternetCloseHandle`
 
        DIM _FILETIME{dwLowDateTime%, dwHighDateTime%}
        DIM findData{dwFileAttributes%, \
        \            ftCreationTime{} = _FILETIME{}, \
        \            ftLastAccessTime{} = _FILETIME{}, \
        \            ftLastWriteTime{} = _FILETIME{}, \
        \            nFileSizeHigh%, nFileSizeLow%, \
        \            dwReserved0%, dwReserved1%, \
        \            cFileName&(259), cAlternate&(13), padding&(1)}
 
        FTPserver$ = "ftp.cs.brown.edu"
        UserName$ = "anonymous"
        Password$ = ""
        Directory$ = "pub"
 
        REM Open an internet connection:
        SYS `InternetOpen`, "BBC BASIC for Windows", OPEN_TYPE_PRECONFIG, 0, 0, 0 TO hOpen%
        IF hOpen% = 0 ERROR 100, "Cannot open internet connection"
 
        REM Connect to the FTP server:
        SYS `InternetConnect`, hOpen%, FTPserver$, FTP_PORT, \
        \                      UserName$, Password$, _INTERNET_SERVICE_FTP, 0 , 0 \
        \                      TO hConnection%
        IF hConnection% = 0 ERROR 100, "Cannot open FTP connection"
 
        REM Set the current directory:
        SYS `FtpSetCurrentDirectory`, hConnection%, Directory$ TO res%
        IF res% = 0 ERROR 100, "Cannot set current directory"
 
        REM List the directory:
        SYS `FtpFindFirstFile`, hConnection%, 0, findData{}, 0, 0 TO hSearch%
        IF hSearch% = 0 ERROR 100, "Cannot list directory contents"
        REPEAT
          PRINT findData.nFileSizeLow% TAB(12) findData.cFileName&()
          SYS `InternetFindNextFile`, hSearch%, findData{} TO res%
        UNTIL res% = 0
 
        REM Close the search:
        SYS `InternetCloseHandle`, hSearch%
 
        REM Close the FTP connection:
        SYS `InternetCloseHandle`, hConnection%
 
        REM Close the internet connection:
        SYS `InternetCloseHandle`, hOpen%