您好,我有下面的C#代码下载按钮点击图像。下载图像使用webclient不工作
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
方法并在标签中打印“下载完成”。我试图下载可变大小的图像,没有运气。 我不知道我的代码有什么问题。有人可以帮我吗?
感谢
mmmh,我不认为你可以做你想做的。基本上,要更新你的lbstatus.Text,你需要发送一个响应给客户端,但为了发送响应,你需要一个请求......我从来没有使用异步代码服务器端,但正如我所看到的你只能用它来更新数据库或发送邮件或任何东西,但再次发送一个响应到客户端... –
@Bartdude,更新标签不是我的问题,代码根本没有下载图像。 – WatsMyName