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 になります。ファイブパーセント変数。最初の試行でストリーム全体を読み取ったように見えます。
チャンクを適切に読み取るようにするにはどうすればよいですか?
ありがとう、
アンドレイ