Visual Basic 6.0
Visual Basic 6.0
Open a Remote File on an SFTP Server
See more SFTP Examples
Demonstrates the Chilkat SFtp.OpenFile method, which opens or creates a remote file and returns a handle for subsequent read or write operations. The arguments are the remote path, the access mode (readOnly, writeOnly, or readWrite), and the create disposition. Close the handle with CloseHandle when finished.
Background: Handle-based access is the foundation for everything the by-name convenience methods hide. The create disposition is the key control — it decides whether a missing file is an error (
openExisting), whether an existing file is truncated (createTruncate) or preserved (openOrCreate), and can add options such as appendData for logging. Because the handle names a server-side resource, it must be closed to avoid exhausting the server's open-file limit.Chilkat Visual Basic 6.0 Downloads
Dim success As Long
success = 0
' Demonstrates the SFtp.OpenFile method, which opens or creates a remote file and returns a
' handle for subsequent read or write operations. The 1st argument is the remote path, the 2nd
' is the access mode, and the 3rd is the create disposition.
Dim sftp As New ChilkatSFtp
' Connect, authenticate, and initialize the SFTP subsystem.
Dim port As Long
port = 22
success = sftp.Connect("sftp.example.com",port)
If (success = 0) Then
Debug.Print sftp.LastErrorText
Exit Sub
End If
' Normally you would not hard-code the password in source. You should instead obtain it
' from an interactive prompt, environment variable, or a secrets vault.
Dim password As String
password = "mySshPassword"
success = sftp.AuthenticatePw("mySshLogin",password)
If (success = 0) Then
Debug.Print sftp.LastErrorText
Exit Sub
End If
success = sftp.InitializeSftp()
If (success = 0) Then
Debug.Print sftp.LastErrorText
Exit Sub
End If
' access must be "readOnly", "writeOnly", or "readWrite".
'
' createDisposition is a comma-separated list containing exactly one primary disposition:
' createNew Create a new file; fail if it already exists.
' createTruncate Create a new file, or open and truncate an existing file.
' openExisting Open an existing file; fail if it does not exist.
' openOrCreate Open the file if it exists, otherwise create it.
' truncateExisting Open and truncate an existing file; fail if it does not exist.
' Optional additional keywords include appendData, textMode, blockRead, blockWrite, and others.
' Open a remote file for reading.
Dim handle As String
handle = sftp.OpenFile("subdir/data.txt","readOnly","openExisting")
If (sftp.LastMethodSuccess = 0) Then
Debug.Print sftp.LastErrorText
Exit Sub
End If
Debug.Print "Opened file, handle = " & handle
' ... read from the handle ...
' Always close the handle when finished.
success = sftp.CloseHandle(handle)
If (success = 0) Then
Debug.Print sftp.LastErrorText
Exit Sub
End If
sftp.Disconnect