使用webclient下载图像无法正常工作

时间:2013-11-25 13:23:14

标签: c# webclient

您好我已经按照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方法并在标签中打印“下载完成”。我尝试下载可变大小的图像,没有运气。 我不确定我的代码有什么问题。有人可以帮我吗?

由于

2 个答案:

答案 0 :(得分:4)

在异步操作完成之前,您无法释放Web客户端。只需将Dispose调用放入Download_Complete(以及错误等等),它就可以正常工作。

答案 1 :(得分:0)

对不起伙计们,

我发现了问题。我不会删除这个帖子,因为将来有人可能会陷入类似的愚蠢错误。

问题是。文件test.jpg正在使用,webclient无法覆盖已在使用的文件。

感谢大家的努力。