【发布时间】:2015-04-17 15:08:46
【问题描述】:
我有以下方法从 FTP 服务器下载文件:
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;
}
然后我有一个使用按钮调用的 BackgroundWorker。 在 BackgroundWorker "DoWork" 事件中,我调用了 DownloadFTP 方法:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (descargaFTP(folder + "\\folder\\", ftpServer+ file, User, Password))
{
MessageBox.Show("Download Completed");
}
}
我想添加一个按钮来取消 FTPDownload。我该怎么做?
【问题讨论】:
标签: c# ftp backgroundworker