I download the file, but after how the Internet is back in battle, it does not continue downloading. How to fix it?

WebClient web = new WebClient(); web.DownloadFileAsync(Uri, Path, DWMVC); 

PS: It is necessary that when the Internet connection is disconnected, the file download stops, and after the Internet is resumed, the remaining files are downloaded again!

  • The entire UI code in your question is superfluous, it makes sense to remove it. The smaller the code, the more likely it is to get a good answer. - VladD
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

Based on the code from the @AkaInq response (added using and checking the return code):

 var request = WebRequest.CreateHttp(uri); var fi = new FileInfo(path); var havePart = fi.Exists; if (havePart) request.AddRange(fi.Length); using (var response = (HttpWebResponse)request.GetResponse()) { var partialDownload = havePart && response.StatusCode == HttpStatusCode.PartialContent; using (var file = File.Open(path, partialDownload ? FileMode.Append : FileMode.Create)) using (var net = response.GetResponseStream()) net.CopyTo(file); } 

Add try / catch to the right place to taste.

    something like that, really, this is not via webclient:

     static void DownloadFile(string sSourceURL, string sDestinationPath) { long iFileSize = 0; int iBufferSize = 1024; iBufferSize *= 1000; long iExistLen = 0; System.IO.FileStream saveFileStream; if (System.IO.File.Exists(sDestinationPath)) { System.IO.FileInfo fINfo = new System.IO.FileInfo(sDestinationPath); iExistLen = fINfo.Length; } if (iExistLen > 0) saveFileStream = new System.IO.FileStream(sDestinationPath, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); else saveFileStream = new System.IO.FileStream(sDestinationPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite); System.Net.HttpWebRequest hwRq; System.Net.HttpWebResponse hwRes; hwRq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(sSourceURL); hwRq.AddRange((int)iExistLen); System.IO.Stream smRespStream; hwRes = (System.Net.HttpWebResponse)hwRq.GetResponse(); smRespStream = hwRes.GetResponseStream(); iFileSize = hwRes.ContentLength; int iByteSize; byte[] downBuffer = new byte[iBufferSize]; while ((iByteSize = smRespStream.Read(downBuffer, 0, downBuffer.Length)) > 0) { saveFileStream.Write(downBuffer, 0, iByteSize); } } 
    • Why not just through Stream.CopyTo ? And you forgot to close the streams, so there will be data loss. - VladD
    • And you should also look at the returned code: 200 or 206. And depending on this, erase the beginning of the downloaded file or not. - VladD
    • Something too big piece of code, and why is Webclient worse? - TriX
    • @TriX HttpWebRequest.AddRange - AkaInq