Chilkat Event Callbacks in C# (.NET Core)

Here’s a C# .NET Core example using the Chilkat .NET Core assembly to perform an SFTP download with support for the following event callbacks:

  • PercentDone — to track download progress
  • AbortCheck — to allow canceling the operation
  • ProgressInfo — to monitor additional info such as transfer rate

While this example focuses on callbacks for an SFTP download, the same method applies to other Chilkat .NET Core classes like Http, Ftp2, MailMan, and Rest.


Important: Event callbacks differ between .NET Core and .NET Framework.

See Chilkat C# Event Callbacks in .NET Framework



private bool _abort = false;

// You can trigger cancellation by setting AbortFlag = true; from another thread.
public bool AbortFlag
{
    get { return _abort; }
    set { _abort = value; }
}


public void handleAbortCheck(out bool abort)
{
    // If abort is true, the operation will be aborted.
    abort = AbortFlag;
}

public void handlePercentDone(int pctDone, out bool abort)
{
    Console.WriteLine($"Progress: {pctDone}%");
    // If abort is true, the operation will be aborted.
    abort = AbortFlag;
}

public void handleProgressInfo(string name, string value)
{
    Console.WriteLine($"[ProgressInfo] {name}: {value}");
}

public void demonstrateEventCallback()
{
    var sftp = new Chilkat.SFtp();

    // Add event callbacks
    Chilkat.SFtp.AbortCheck abortCheck = new Chilkat.SFtp.AbortCheck(handleAbortCheck);
    sftp.setAbortCheckCb(abortCheck);

    Chilkat.SFtp.PercentDone percentDone = new Chilkat.SFtp.PercentDone(handlePercentDone);
    sftp.setPercentDoneCb(percentDone);

    Chilkat.SFtp.ProgressInfo progressInfo = new Chilkat.SFtp.ProgressInfo(handleProgressInfo);
    sftp.setProgressInfoCb(progressInfo);


    // Connect to SFTP server
    if (!sftp.Connect("sftp.example.com", 22))
    {
        Console.WriteLine("Connect failed: " + sftp.LastErrorText);
        return;
    }

    if (!sftp.AuthenticatePw("username", "password"))
    {
        Console.WriteLine("Auth failed: " + sftp.LastErrorText);
        return;
    }

    if (!sftp.InitializeSftp())
    {
        Console.WriteLine("Init failed: " + sftp.LastErrorText);
        return;
    }

    // File to download
    string remotePath = "remote/path/file.txt";
    string localPath = "C:\\Temp\\file.txt";

    // Perform download
    if (!sftp.DownloadFileByName(remotePath, localPath))
    {
        Console.WriteLine("Download failed: " + sftp.LastErrorText);
        return;
    }

    Console.WriteLine("Download completed.");

}