Question

I am trying to download data using a Webclient object in chunks of 5% each. The reason is that I need to report progress for each downloaded chunk.

Here is the code I wrote to do this task:

    private void ManageDownloadingByExtractingContentDisposition(WebClient client, Uri uri)
    {
        //Initialize the downloading stream 
        Stream str = client.OpenRead(uri.PathAndQuery);

        WebHeaderCollection whc = client.ResponseHeaders;
        string contentDisposition = whc["Content-Disposition"];
        string contentLength = whc["Content-Length"];
        string fileName = contentDisposition.Substring(contentDisposition.IndexOf("=") +1);

        int totalLength = (Int32.Parse(contentLength));
        int fivePercent = ((totalLength)/10)/2;

        //buffer of 5% of stream
        byte[] fivePercentBuffer = new byte[fivePercent];

        using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
        {
            int count;
            //read chunks of 5% and write them to file
            while((count = str.Read(fivePercentBuffer, 0, fivePercent)) > 0);
            {
                fs.Write(fivePercentBuffer, 0, count);
            }
        }
        str.Close();
    }

The problem - when it gets to str.Read(), it pauses as much as reading the whole stream, and then count is 0. So the while() doesn't work, even if I specified to read only as much as the fivePercent variable. It just looks like it reads the whole stream in the first try.

How can I make it so that it reads chunks properly?

Thanks,

Andrei

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top