Sample code for 30+ languages & platforms
PureBasic

SFTP Upload and Download to a StringBuilder Object

See more SFTP Examples

Demonstrates how to SFTP upload from a Chilkat StringBuilder object, and download into a StringBuilder object.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkSFtp.pb"

Procedure ChilkatExample()

    success.i = 0

    ; This example requires the Chilkat API to have been previously unlocked.
    ; See Global Unlock Sample for sample code.

    sftp.i = CkSFtp::ckCreate()
    If sftp.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ; Set some timeouts, in milliseconds:
    CkSFtp::setCkConnectTimeoutMs(sftp, 5000)
    CkSFtp::setCkIdleTimeoutMs(sftp, 10000)

    ; Connect to the SSH server and then authenticate.
    port.i = 22
    success = CkSFtp::ckConnect(sftp,"MY-SSH-SERVER-DOMAIN-OR-IP",port)
    If success = 1
        success = CkSFtp::ckAuthenticatePw(sftp,"MY-SSH-LOGIN","MY-SSH-PASSWORD")
        If success = 1
            success = CkSFtp::ckInitializeSftp(sftp)
        EndIf

    EndIf

    If success <> 1
        Debug CkSFtp::ckLastErrorText(sftp)
        CkSFtp::ckDispose(sftp)
        ProcedureReturn
    EndIf

    sbA.i = CkStringBuilder::ckCreate()
    If sbA.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkStringBuilder::ckLoadFile(sbA,"qa_data/hamlet.xml","utf-8")

    ; Upload the contents of sbA to the SSH/SFTP server.
    bIncludeBOM.i = 0
    remotePath.s = "sftpTesting/hamlet.xml"
    success = CkSFtp::ckUploadSb(sftp,sbA,remotePath,"utf-8",bIncludeBOM)
    If success <> 1
        Debug CkSFtp::ckLastErrorText(sftp)
        CkSFtp::ckDispose(sftp)
        CkStringBuilder::ckDispose(sbA)
        ProcedureReturn
    EndIf

    ; Download the file..
    sbB.i = CkStringBuilder::ckCreate()
    If sbB.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkSFtp::ckDownloadSb(sftp,remotePath,"utf-8",sbB)
    If success <> 1
        Debug CkSFtp::ckLastErrorText(sftp)
        CkSFtp::ckDispose(sftp)
        CkStringBuilder::ckDispose(sbA)
        CkStringBuilder::ckDispose(sbB)
        ProcedureReturn
    EndIf

    ; Verify that sbA and sbB have the exact same contents.
    Debug "size of sbA: " + Str(CkStringBuilder::ckLength(sbA))
    bCaseSensitive.i = 1
    If CkStringBuilder::ckContentsEqualSb(sbA,sbB,bCaseSensitive) = 1
        Debug "Contents are equal. Success."
    Else
        Debug "Contents are NOT equal.  Failed."
    EndIf

    CkSFtp::ckDisconnect(sftp)


    CkSFtp::ckDispose(sftp)
    CkStringBuilder::ckDispose(sbA)
    CkStringBuilder::ckDispose(sbB)


    ProcedureReturn
EndProcedure