How to Easily Use FTP in WSH - Uploading and Downloading files
(Page 2 of 4 )
It’s obviously not enough to just connect to an FTP server. You undoubtedly have some task to perform. One of the most common is a file download. Let’s take a look at how to create a simple function for performing file downloads with the Chilkat FTP component.
In order to download a file we need to provide three pieces of information: what file to download, where to save it locally, and where to find it on the remote server. We’ll pass these values as parameters to our function.
Our function first needs to navigate to the proper remote directory. We can do this with the ChangeRemoteDir method provided by the Chilkat component.
Function FileDownload(rFile, lFile, rDir)
If objFtp.IsConnected Then
success = objFtp.ChangeRemoteDir(rDir)
If (success <> 1) Then
FileDownload = objFtp.LastErrorText
Exit Function
End If
Finally, we can get the file that we wish to download using the GetFile method.
success = objFtp.GetFile(rFile, lFile)
If (success <> 1) Then
FileDownload = objFtp.LastErrorText
Exit Function
End If
FileDownload = "ok"
End If
End Function
Notice that I’ve wrapped the entire function inside of an IF statement that uses the IsConnected method to make sure that the connection to the FTP server is still active. We could provide a subroutine that would reconnect if necessary.
Also notice that I’ve continually caught the return code for each procedure I’ve performed. If you were implementing this code in a real world situation, it would be in your best interest to add some error-handling or logging.
To perform a file upload, we just perform the opposite function. Notice how similar the two functions are.
Function FileUpload(lFile, rFile, rdir)
If objFtp.IsConnected Then
success = objFtp.ChangeRemoteDir(rDir)
If (success <> 1) Then
FileUpload = objFtp.LastErrorText
Exit Function
End If
success = objFtp.PutFile(lFile,rFile)
If (success <> 1) Then
FileUpload = objFtp.LastErrorText
Exit Function
End If
FileUpload = "ok"
End If
End Function
Now we can use these functions from anywhere in our script as long as we have an active FTP connection.
result1 = FileDownload("index.old", "index.html", "/public_html/ircstats")
result2 = FileUpload("FtpTest.vbs", "FtpTest.vbs", "/public_html/ircstats")
Next: Extending the Chilkat FTP ActiveX control >>
More Windows Scripting Articles
More By Nilpo