Chilkat Event Callbacks in C# (.NET Framework)
Here’s a C# .NET Framework example using the Chilkat .NET Framework assembly to perform an SFTP download with support for the following event callbacks:
PercentDone
— to track download progressAbortCheck
— to allow canceling the operationProgressInfo
— 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 Framework classes like Http, Ftp2, MailMan, and Rest.
Important: Event callbacks differ between .NET Core and .NET Framework.
See Chilkat C# Event Callbacks in .NET Core
private bool _abort = false;
// You can trigger cancellation by setting AbortFlag = true; from another thread.
public bool AbortFlag
{
get { return _abort; }
set { _abort = value; }
}
private void Sftp_OnProgressInfo(object sender, ProgressInfoEventArgs args)
{
Console.WriteLine($"[ProgressInfo] {args.Name}: {args.Value}");
}
private void Sftp_OnPercentDone(object sender, PercentDoneEventArgs args)
{
Console.WriteLine($"Progress: {args.PercentDone}%");
// If args.Abort is true, the operation will be aborted.
args.Abort = AbortFlag;
}
private void Sftp_OnAbortCheck(object sender, AbortCheckEventArgs args)
{
// If args.Abort is true, the operation will be aborted.
args.Abort = AbortFlag;
}
private void SFtpDownload()
{
var sftp = new Chilkat.SFtp();
sftp.OnAbortCheck += Sftp_OnAbortCheck;
sftp.OnPercentDone += Sftp_OnPercentDone;
sftp.OnProgressInfo += Sftp_OnProgressInfo;
// 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.");
}