C# 使用webclient下载图像不工作
您好,我有以下C#代码下载按钮点击图像C# 使用webclient下载图像不工作,c#,webclient,C#,Webclient,您好,我有以下C#代码下载按钮点击图像 private void DownloadCover() { try { string SaveFileLocation = AppDomain.CurrentDomain.BaseDirectory + "\\data\\covers\\test.jpg" ; WebClient webClient = new WebClient(); string cURL = "http://uploa
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
。只要点击按钮,它就会立即转到downloadplete
方法,并在标签中打印“downloadplete”。我尝试下载可变大小的图像,但没有成功。
我不确定我的代码出了什么问题。有人能帮我吗
谢谢在异步操作完成之前,您无法处理web客户端。只需将Dispose调用放入您的下载中即可完成(以及错误等),它应该可以工作。在异步操作完成之前,您无法处理web客户端。只需将Dispose调用放入您的下载中即可完成(以及错误等),它应该可以工作。抱歉,伙计们 我发现了问题。我不会删除这个帖子,因为将来有人可能会犯类似的愚蠢错误 问题是。文件test.jpg正在使用,webclient无法覆盖已在使用的文件 谢谢大家的努力。对不起,伙计们 我发现了问题。我不会删除这个帖子,因为将来有人可能会犯类似的愚蠢错误 问题是。文件test.jpg正在使用,webclient无法覆盖已在使用的文件
谢谢大家的努力。mmmh,我认为你不能做你想做的事。基本上,要更新lbstatus.Text,您需要向客户端发送响应,但要发送响应,您需要请求。。。我从来没有在服务器端使用过异步代码,但在我看来,你只能用它来更新数据库或发送邮件或其他任何东西,而不能再次向客户端发送响应…@Bartdude,更新标签不是我的问题,代码根本没有下载图像。嗯,我认为你不能做你想做的事情。基本上,要更新lbstatus.Text,您需要向客户端发送响应,但要发送响应,您需要请求。。。我从未在服务器端使用过异步代码,但在我看来,您只能使用它来更新数据库或发送邮件或其他任何东西,而不能再次向客户端发送响应…@Bartdude,更新标签不是我的问题,代码根本没有下载图像。