I have the following method to download files from an FTP server:
public bool DownloadFTP(string LocalDirectory, string RemoteFile,
string Login, string Password)
{
try
{
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(RemoteFile);
ftp.Credentials = new NetworkCredential(Login, Password);
ftp.KeepAlive = false;
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
Form1 form = new Form1();
ftp.UseBinary = true;
long pesoarchivo = obtenertamano(RemoteFile, Login, Password);
ftp.Proxy = null;
ftp.EnableSsl = false;
LocalDirectory = Path.Combine(LocalDirectory, Path.GetFileName(RemoteFile));
using (FileStream fs = new FileStream(LocalDirectory, FileMode.Create,
FileAccess.Write, FileShare.None))
using (Stream strm = ftp.GetResponse().GetResponseStream())
{
int buffLength = 2048;
byte[] buff = new byte[buffLength];
// Leer del buffer 2kb cada vez
int contentLen=strm.Read(buff, 0, buffLength);
int bytes = 0;
try
{
while (contentLen > 0)
{
fs.Write(buff, 0, contentLen);
contentLen = strm.Read(buff, 0, buffLength);
bytes += contentLen;
int totalSize = (int)(pesoarchivo) / 1000;
if (bytes != 0)
{
// Console.WriteLine(((bytes / 1000) * 100 / totalSize).ToString()+" "+ totalSize.ToString());
backgroundWorker1.ReportProgress((bytes / 1000) * 100 / totalSize, totalSize);
// label1.Text = ((bytes / 1000) * 100 / totalSize).ToString();
}
else { }
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString()) }
}
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString())
return false;
}
Then I have a BackgroundWorker I called using a button. On the BackgroundWorker "DoWork" event I call the DownloadFTP method:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (descargaFTP(folder + "\\folder\\", ftpServer+ file, User, Password))
{
MessageBox.Show("Download Completed");
}
}
I want to add a button to cancel the FTPDownload. How can I do it?