【发布时间】:2013-11-25 13:23:14
【问题描述】:
您好,我有以下 C# 代码可在单击按钮时下载图像。
private void DownloadCover()
{
try
{
string SaveFileLocation = AppDomain.CurrentDomain.BaseDirectory + "\\data\\covers\\test.jpg" ;
WebClient webClient = new WebClient();
string cURL = "http://upload.wikimedia.org/wikipedia/commons/4/45/Right-facing-Arrow-icon.jpg";
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompleted);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressChanged);
webClient.DownloadFileAsync(new Uri(cURL), SaveFileLocation);
webClient.Dispose();
}
catch (Exception exd)
{
ErrorLogger.LogError(exd.ToString());
}
}
private void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
lbStatus.Text = "Downloading Cover..." + e.ProgressPercentage + "%";
}
private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
{
try
{
lbStatus.Text = "Download Complete";
string CoverPath = AppDomain.CurrentDomain.BaseDirectory + "\\data\\covers\\test.jpg";
coverImage.Image = new Bitmap(CoverPath);
}
catch (Exception ex)
{
ErrorLogger.LogError(ex.ToString());
}
}
private void btnDownloadImage_Click(object sender, EventArgs e)
{
DownloadCover();
}
单击按钮时,代码永远不会执行下载进度更改处理方法DownloadProgressChanged。每当单击按钮时,它会立即转到DownloadComplete 方法并在标签中打印“下载完成”。我尝试下载可变大小的图像,但没有成功。
我不确定我的代码有什么问题。有人可以帮我吗?
谢谢
【问题讨论】:
-
嗯,我不认为你能做你想做的事。基本上,要更新您的 lbstatus.Text,您需要向客户端发送响应,但为了发送响应,您需要一个请求......我从未在服务器端使用过异步代码,但正如我所见您只能使用它来更新数据库或发送邮件或其他任何东西,但再次向客户端发送响应......
-
@Bartdude,更新标签不是我的问题,代码根本没有下载图像。