How to check if a file exists in the FTP server



This blog post shows how to check if a file exists in the FTP server. The shown example tries to download a file only if it exists but if it does not exist it creates an empty file locally. The filename here is EXAMPLE.txt but it can be any other name.

Beware that this script does not go through all the directory tree in the FTP server searching for the file. It only checks one directory (/remotedir) and does not go through subdirectories. This is done getting the file list first with GETLIST and then we use FOREACH to compare every file name we got in the previous step with the text string “EXAMPLE.txt”:

 

# Connect to the server
# Get the list of remote files
 GETLIST($my_remote_files, REMOTE_FILES)
 
# We will save in this variable whether or not the file exists
 $exists="no"
 
# Go one by one through the list of remote files
 FOREACH $file IN $my_remote_files
     IF($file=="EXAMPLE.txt")
          $exists="yes"
     END IF
 END FOREACH

The empty txt file we create in the case the remote TXT file does not exist is created with the windows command line command:

type NUL > EXAMPLE.txt

Within ScriptFTP this is launched with the EXEC command:

EXEC("type NUL > EXAMPLE.txt")

 

The full script is the following:

 

# Connect to the server
 OPENHOST("127.0.0.1","test","1234")
 
# Set the current local directory. Files will be downloaded here
 LOCALCHDIR("C:\Users\test\Desktop")
 
# Set the current remote directory
 CHDIR("/remotedir")
 
# Get the list of remote files
 GETLIST($my_remote_files, REMOTE_FILES)
 
# We will save in this variable whether or not the file exists
 $exists="no"
 
# Go one by one through the list of remote files
 FOREACH $file IN $my_remote_files
     IF($file=="EXAMPLE.txt")
          $exists="yes"
     END IF
 END FOREACH
 
# If it exists download it. if not create an empty txt file
 IF($exists=="yes")
      GETFILE("EXAMPLE.txt")
 ELSE
      EXEC("type NUL > EXAMPLE.txt")
 END IF
 
CLOSEHOST