Sample code for 30+ languages & platforms
Lianja

Write Text to a Remote SFTP File (Sequential)

See more SFTP Examples

Demonstrates the Chilkat SFtp.WriteFileText method, which encodes text using a charset and writes it at the current sequential write position of an open handle. The arguments are the handle, the charset, and the text.

Background: Chilkat tracks a write position per handle, so successive WriteFileText calls append naturally — the pattern for building a file a piece at a time, such as writing rows to a report. Opening with openOrCreate starts writing at the current end of the file. The charset determines the bytes actually stored, which matters whenever the text contains non-ASCII characters.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

//  Demonstrates the SFtp.WriteFileText method, which encodes text and writes it at the current
//  sequential write position of an open handle.  The 1st argument is the handle, the 2nd is the
//  charset, and the 3rd is the text.

loSftp = createobject("CkSFtp")

//  Connect, authenticate, and initialize the SFTP subsystem.
lnPort = 22
llSuccess = loSftp.Connect("sftp.example.com",lnPort)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

//  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.
lcPassword = "mySshPassword"

llSuccess = loSftp.AuthenticatePw("mySshLogin",lcPassword)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

llSuccess = loSftp.InitializeSftp()
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

//  Open (creating/truncating) the remote file for writing.
lcHandle = loSftp.OpenFile("subdir/notes.txt","writeOnly","createTruncate")
if (loSftp.LastMethodSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

//  Write text as UTF-8.  Successive writes continue from where the previous write ended.
llSuccess = loSftp.WriteFileText(lcHandle,"utf-8","First line." + Chr(10))
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

llSuccess = loSftp.WriteFileText(lcHandle,"utf-8","Second line." + Chr(10))
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

llSuccess = loSftp.CloseHandle(lcHandle)
if (llSuccess = .F.) then
    ? loSftp.LastErrorText
    release loSftp
    return
endif

? "Wrote text file."

loSftp.Disconnect()


release loSftp