This code block downloads images from a website.. I used WebClient at one time and I had used DownloadFileAsync combined with my own event handler to send the main form the message that a file was downloaded.

Now I am using HttpWebRequest to try and improve download speed, however I cannot find a way to tell when the file has successfully download!

Can anyone help?

private void Download(object data)
        {
            Data tmp = (Data)data;
            string dl = tmp.url;
            string filename = "";

            Directory.CreateDirectory(tmp.saveTo);

            if (dl != ".././")
            {

                HttpWebRequest web = (HttpWebRequest)WebRequest.Create(tmp.url);
                HttpWebResponse httpWebResponse = (HttpWebResponse)web.GetResponse();
                Stream stream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(stream, Encoding.ASCII);

                try
                {
                    filename = dl.Substring(dl.LastIndexOf("/") + 1, dl.LastIndexOf(".") - dl.LastIndexOf("/") + 3);
                }
                catch { }

                //web.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(web_DownloadFileCompleted);

                try
                {
                    Image _tmpImage = Image.FromStream(stream);
                    _tmpImage.Save(tmp.saveTo + "\\" + filename);
                    //web.DownloadFileAsync(new Uri(dl), @tmp.saveTo + @"\" + filename + tmp.url.Substring(tmp.url.LastIndexOf("."),4));
                }
                catch {
                    Download(tmp);
                }
                
            }

            
        }

Your web.GetResponse() is what actually begins the file transfer. In this case, you would need to use BeginGetResponse(), which makes a callback to a method you designate:

http://msdn.microsoft.com/en-us/library/system.net.webrequest.begingetresponse.aspx

Check that out, and see if it's any further help. You could make the callback method do the updating to the form, or you could have it raise the event that is handled elsewhere.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.