My application downloads huge files using HttpWebRequest -> WebResponse -> Stream -> FileStream
. See code below.
With following the scenario we always get corrupted files:
- 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.
Problem: the downloaded file is corrupted.
I'm sure this is common problem, but I failed googling or SOing it. Please advise. What can be the cause?
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);
}
}
}