HttpWebRequest -> WebResponse -> Stream -> FileStream
. 参见下面的代码。
-
开始下载。
-
拔下电缆或单击以暂停下载过程。
-
关闭并打开应用程序。
-
开始下载(从中断点开始)。
-
问题:下载的文件已损坏。
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);
}
}
}