I need to make a button that will stop downloading the file. For example, I clicked 1 time the download started and the second time it stopped.
private static async void Download()
{
foreach (string fileName in fileList)
{
string localDir = AppDomain.CurrentDomain.BaseDirectory;
localDir.Substring(0, localDir.Length - 1);
localDir += fileName;
long fileSize = await ftp.GetFileSizeAsync(fileName);
fileSize /= 1024;
form.progressBar1.Maximum = (int)fileSize;
var token = new CancellationToken();
Progress<FtpProgress> progress = new Progress<FtpProgress>(async loadedFile =>
{
if (loadedFile.Progress == 100)
{
form.progressBar1.Value = 0;
}
else
{
int x = (int)fileSize * Convert.ToInt32(loadedFile.Progress) / 100;
string value = loadedFile.TransferSpeedToString();
form.label1.Text = "Connection Speed: \n" + value;
form.progressBar1.Value = x;
}
});
await ftp.DownloadFileAsync(localDir, fileName, FtpLocalExists.Skip, FluentFTP.FtpVerify.Retry, progress, token);
}
}
First of all, you don't create directly a CancellationToken
, you create a CancellationTokenSource
and get it's Token
.
Said that, you can imagine the use of that token, to allow to cancel the operation. You can do something like this:
//At class level
CancellationTokenSource cancel = null;
private static async void Download()
{
if(cancel != null)
{
cancel.Cancel();
cancel.Dispose();
cancel = null;
return;
}
cancel = new CancellationTokenSource();
foreach (string fileName in fileList)
{
string localDir = AppDomain.CurrentDomain.BaseDirectory;
localDir.Substring(0, localDir.Length - 1);
localDir += fileName;
long fileSize = await ftp.GetFileSizeAsync(fileName);
fileSize /= 1024;
form.progressBar1.Maximum = (int)fileSize;
Progress<FtpProgress> progress = new Progress<FtpProgress>(async loadedFile =>
{
if (loadedFile.Progress == 100)
{
form.progressBar1.Value = 0;
cancel.Dispose();
cancel = null;
}
else
{
int x = (int)fileSize * Convert.ToInt32(loadedFile.Progress) / 100;
string value = loadedFile.TransferSpeedToString();
form.label1.Text = "Connection Speed: \n" + value;
form.progressBar1.Value = x;
}
});
try
{
await ftp.DownloadFileAsync(localDir, fileName, FtpLocalExists.Skip, FluentFTP.FtpVerify.Retry, progress, cancel.Token);
}
catch
{
//When the download is cancelled will throw an exception
//you can create a more specific handler
cancel.Dispose();
cancel = null;
}
}
}