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 になります。ファイブパーセント変数。最初の試行でストリーム全体を読み取ったように見えます。

チャンクを適切に読み取るようにするにはどうすればよいですか?

ありがとう、

アンドレイ

4

3 に答える 3

3

while ループの行末にセミコロンがあります。私はそれに気付くまで、なぜ受け入れられた答えが正しいのかについて非常に混乱していました.

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