WebClient.OpenRead以块的形式下载数据

时间:2011-09-14 23:16:48

标签: c# stream webclient chunks

我正在尝试使用Webclient对象以5%的每个块下载数据。原因是我需要报告每个下载的块的进度。

以下是我为执行此任务而编写的代码:

    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();
    }

问题 - 当它到达str.Read()时,它会暂停读取整个流,然后count为0.所以while()不起作用,即使我指定只读取为就像fivePercent变量一样。看起来它只是在第一次尝试时读取整个流。

如何才能正确读取块?

谢谢,

安德烈

3 个答案:

答案 0 :(得分:3)

你的while循环在行尾有一个分号。我很困惑为什么接受的答案是对的,直到我注意到了。

答案 1 :(得分:1)

如果您不需要精确的5%块大小,您可能需要查看异步下载方法,例如DownloadDataAsyncOpenReadAsync

每次下载新数据并且进度发生变化时,它们都会触发DownloadProgressChanged事件,并且事件会在事件参数中提供完成百分比。

一些示例代码:

WebClient client = new WebClient();
Uri uri = new Uri(address);

// Specify a progress notification handler.
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);

client.DownloadDataAsync(uri);

static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
    // Displays the operation identifier, and the transfer progress.
    Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...", 
        (string)e.UserState, 
        e.BytesReceived, 
        e.TotalBytesToReceive,
        e.ProgressPercentage);
}

答案 2 :(得分:1)

do
{
    count = str.Read(fivePercentBuffer, 0, fivePercent);
    fs.Write(fivePercentBuffer, 0, count);
} while (count > 0);