The Range header cannot be installed explicitly through the Headers collection: https://msdn.microsoft.com/en-us/library/system.net.webclient.headers.aspx .
When you start downloading the file, you will get a WebException exception with the message
You need to be modified using the appropriate property or method
However, you can create a WebClient descendant by correcting this error in it. I think it’s MyWebClient to replace WebClient with MyWebClient everywhere:
class MyWebClient: WebClient { private int _position; // установка позиции, откуда будет возобновлено скачивание public void SetFromPosition(int position) { _position = position; } protected override WebRequest GetWebRequest(Uri address) { var request = (HttpWebRequest) base.GetWebRequest(address); // если позиция задана, установим заголовок range легальным способом if (_position > 0) request.AddRange(_position); return request; } }
Example of use:
var client = new MyWebClient(); var info = new FileInfo(file); if (info.Exists) { client.SetFromPosition((int)info.Length); } client.DownloadFileAsync(new Uri(url), file); // ...
Method for resuming file:
public new void DownloadFile(Uri url, string file) { using (var fs = new FileStream(file, FileMode.Append, FileAccess.Write)) { using (var response = OpenRead(url)) { response.CopyTo(fs); } } }
An example of loading into a temporary file with the subsequent merging of files:
var client = new MyWebClient(); string tmpFile = file + ".bak"; // временный файл c.DownloadFileCompleted += (sender, args) => { // дозапись из src в dest using (var dest = new FileStream(file, FileMode.Append, FileAccess.Write)) { using (var src = new FileStream(tmpFile, FileMode.Open, FileAccess.Read)) { src.CopyTo(dest); } } File.Delete(tmpFile); }; var info = new FileInfo(file); if (info.Exists) { client.SetFromPosition((int)info.Length); } c.DownloadFileAsync(new Uri(url), tmpFile);