I am trying to download several files from those selected in a list view.
The download works ok for a single files but fails when I select more than on file. I only ever can get the first file to download and show the progress bar.
I know that my code is providing the correct uri because of the line
lbl_DownloadFile.Text = uri + " - Bytes " + bytes_total.ToString() displays the correct file but for some reason _WebClient.DownloadFile(new Uri(uri), destinationfile) gets the file with zero bytes and never downloads.
Any help where i am going wroung would be appeaciated.
Issue found in this code
_WebClient.OpenRead(uri);
Int64 bytes_total= Convert.ToInt64(_WebClient.ResponseHeaders["Content-Length"]);
lbl_DownloadFile.Text = uri + " - Bytes " + bytes_total.ToString() ;
The web client is remaining open will try a procedure to get the above data.
private void _DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
pb_Download.Enabled = Enabled;
lbl_DownloadFile.Text = "Download completed";
if (currentitem < checkedItems.Count)
{
currentitem++;
DownloadNextFile();
}
}
private void _DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void Pb_DownloadClick(object sender, EventArgs e)
{
_WebClient = new System.Net.WebClient();
_WebClient.Credentials = new System.Net.NetworkCredential(this.tb_Username.Text.Trim(),this.tb_Password.Text.Trim());
_WebClient.Headers.Add("Accept-Encoding", "");
checkedItems = lv_Materials.CheckedItems;
DownloadNextFile();
}
void DownloadNextFile()
{
ListViewItem item = checkedItems[currentitem];
DownloadFile(this.tb_WebPage.Text + item.Tag.ToString(), "");
}
void DownloadFile(string uri, string destinationfile)
{
string pathDownload = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
if (String.IsNullOrEmpty(destinationfile))
destinationfile = Path.Combine(pathDownload,uri.Substring(uri.LastIndexOf("/")+1));
pb_Download.Enabled = false;
_WebClient.OpenRead(uri);
Int64 bytes_total= Convert.ToInt64(_WebClient.ResponseHeaders["Content-Length"]);
lbl_DownloadFile.Text = uri + " - Bytes " + bytes_total.ToString() ;
this.progressBar1.Value = 0;
_WebClient.DownloadFileCompleted += new AsyncCompletedEventHandler(_DownloadFileCompleted);
_WebClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_DownloadProgressChanged);
_WebClient.DownloadFileAsync(new Uri(uri), destinationfile);
}
}