Download file with DownloadFile method of the WebClient class

M

Mark

Hello.

I'm downloading some file from some http resource to file on my local disk
with DownloadFile method of the WebClient class.
Since the file is pretty large I want to show the downloading process in
progress bar.

Can anybody advice me how can I do this?

Thank you.
 
M

Morten Wennevik

Hi Mark,

I think you need to use the HttpWebRequest/Response and handle the Stream
downloading.

Read the Stream in a loop and update the progress in each pass.
 
M

Morten Wennevik

There is a quite good example in the documentations on

HttpWebResponse.GetResponseStream()

using that example substitute the code following the line

Stream receiveStream = myHttpWebResponse.GetResponseStream();

with something like this

byte[] data = ReadStream(receiveStream);
FileStream fs = File.Create("myfile.dat");
fs.Write(data, 0, data.Length);
fs.Close();

....

private byte[] ReadStream(Stream receiveStream)
{
byte[] buffer = new byte[4096]; // size of the buffer can be adjusted for
speed optimization

using(MemoryStream ms = new MemoryStream())
{
while(true)
{
int count = receiveStream.Read(buffer, 0, buffer.Length);

if(count <= 0) // no more to read, or possibly no feed
return ms.ToArray();

ms.Write(buffer, 0, read);
// update read status here
// unless you are doing multiple threads with invokes
// you will also want to do an Application.DoEvents()
// or nothing will appear to be updated
label1.Text = ms.Length + " bytes read";
Application.DoEvents();
}
}

PS! this code is untested and may contain typos.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top