我的申请使用<代码>下载了大量档案。 HttpWebRequest -> WebResponse -> Petro -> fileStream。 见下文守则。
根据这一设想,我们总是得到腐败的档案:
- Start download.
- Unplug cable or click to pause download process.
- Close and open the application.
- Start download (it starts from the interruption point).
- Wait full file is downloaded.
问题:下载的档案被腐蚀。
我确信这是一个共同的问题,但我没有这样做。 请提出咨询意见。 原因何在?
public class Downloader
{
int StartPosition { get; set; }
int EndPosition { get; set; }
bool Cancelling { get; set; }
void Download(string[] args)
{
string uri = @"http://www.example.com/hugefile.zip";
string localFile = @"c:hugefile.zip";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AddRange(this.StartPosition);
WebResponse response = request.GetResponse();
Stream inputStream = response.GetResponseStream();
using (FileStream fileStream = new FileStream(localFile, FileMode.Open, FileAccess.Write))
{
int buffSize = 8192;
byte[] buffer = new byte[buffSize];
int readSize;
do
{
// reads the buffer from input stream
readSize = inputStream.Read(buffer, 0, buffSize);
fileStream.Position = this.StartPosition;
fileStream.Write(buffer, 0, (int)readSize);
fileStream.Flush();
// increase the start position
this.StartPosition += readSize;
// check if the stream has reached its end
if (this.EndPosition > 0 && this.StartPosition >= this.EndPosition)
{
this.StartPosition = this.EndPosition;
break;
}
// check if the user have requested to pause the download
if (this.Cancelling)
{
break;
}
}
while (readSize > 0);
}
}
}