0

我正在尝试使用 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() 时,它会暂停读取整个流,然后计数为 0。所以 while() 不起作用,即使我指定只读取五百分变量。看起来它在第一次尝试时读取了整个流。

我怎样才能使它正确读取块?

谢谢,

安德烈

4

3 回答 3

3

您的 while 循环在行尾有一个分号。我很困惑为什么接受的答案是正确的,直到我注意到这一点。

于 2012-02-27T21:53:26.627 回答
1

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

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

一些示例代码:

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);
}
于 2011-09-14T23:25:26.693 回答
1
do
{
    count = str.Read(fivePercentBuffer, 0, fivePercent);
    fs.Write(fivePercentBuffer, 0, count);
} while (count > 0);
于 2011-09-15T14:13:39.910 回答