Reputation: 4478
Hello i have following C# code to download image on button click.
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();
}
When the button is clicked, the code never gets to execute the download progress change handling method DownloadProgressChanged
. Whenever button is click, it instantly goes to DownloadComplete
method and prints "Download Complete" in a label. I tried downloading variable size image with no luck.
I m not sure what is wrong with my code. Can anybody please help me here?
Thanks
Upvotes: 0
Views: 444
Reputation: 4478
Sorry guys,
I found the problem. I m not deleting this thread as someone might stump into similar silly mistake in future.
The problem was. The file test.jpg was in use and webclient was not being able to overwrite the file that is already in use.
Thanks everyone for the effort.
Upvotes: 0
Reputation: 63732
You can't dispose the web client before the asynchronous operation completes. Simply put the Dispose call into your Download_Complete (and error and whatever) and it should work.
Upvotes: 4