我有从ftp下载的代码,并希望将其放入后台工作。
void BtnDownloadClick(object sender, EventArgs e)
{
FolderBrowserDialog fldDlg = new FolderBrowserDialog();
if (fldDlg.ShowDialog() == DialogResult.OK)
Download(fldDlg.SelectedPath, lstFiles.SelectedItem.ToString());
}
private void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + PathFolders + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(Username, Password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
}
}
你能帮帮我吗?我是C#的新手......
提前谢谢!
答案 0 :(得分:0)
简单的方法是使用:
Task.Factory.StartNew(() => Download(fldDlg.SelectedPath, lstFiles.SelectedItem.ToString());
这将使用Asychronous任务来完成下载。由于您的UI不依赖于下载中的任何代码,因此可以正常工作。如果您的下载过程需要在完成后集成回UI,那么最好使用BackgroundWorker。但是,在这种情况下,我认为您可以使用任务。