在C#WPF中恢复下载

时间:2019-01-03 16:49:32

标签: c# cookies webclient

我正在开发WPF应用程序,该应用程序将下载一些大于100 MB的MSI文件。下载时,如果互联网断开连接,则必须从中断下载的位置恢复当前正在下载的文件。我使用了WebClient和Cookies来下载文件。如果互联网断开连接并重新连接,则文件不会恢复。我使用了以下代码。谁能建议我如何实现简历流程?

using (CookieAwareWebClient client = new CookieAwareWebClient())
{
        client.DownloadProgressChanged += WebClientDownloadProgressChanged;
   client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);      
  client.DownloadFileAsync(url, fileName);
 }

static void WebClientDownloadProgressChanged(object sender, 
DownloadProgressChangedEventArgs e)
    {
        Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
        Console.WriteLine(e.BytesReceived.ToString());

    }

    static void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
        Console.WriteLine("Download finished!");
    }       

}

public class CookieAwareWebClient : WebClient
{
    private readonly CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = m_container;
        }
        return request;
    }
}

1 个答案:

答案 0 :(得分:0)

要恢复下载,可以再次建立连接并指定要下载的数据的偏移量。此外,您还可以请求下载一部分数据。

  // establishing the connection
  HttpWebRequest oHttpWebRequest = (HttpWebRequest) WebRequest.Create ("myHttpAddress");

  #if partialDownload

  // reading the range 1000-2000 of the data
  oHttpWebRequest.AddRange (1000, 2000);
  // creating the file
  FileInfo oFileInfo = new FileInfo ("myFilename");
  FileStream oFileStream = oFileInfo.Create ();

  #else

  // reading after the last received byte
  FileInfo oFileInfo = new FileInfo ("myFilename");
  oHttpWebRequest.AddRange (oFileInfo.Length);
  // opening the file for appending the data
  FileStream oFileStream = File.Open (oFileInfo.FullName, FileMode.Append);

  #endif

  // opening the connection
  HttpWebResponse oHttpWebResponse = (HttpWebResponse) oHttpWebRequest.GetResponse ();
  Stream oReceiveStream = oHttpWebResponse.GetResponseStream ();

  // reading the HTML stream and writing into the file
  byte [] abBuffer = new byte [1000000];
  int iReceived = oReceiveStream.Read (abBuffer, 0, abBuffer.Length);
  while ( iReceived > 0 )
  { 
    oFileStream.Write (abBuffer, 0, iReceived);
    iReceived = oReceiveStream.Read (abBuffer, 0, abBuffer.Length);
  };
  // closing and disposing the resources
  oFileStream     .Close   ();
  oFileStream     .Dispose ();
  oReceiveStream  .Close   ();
  oReceiveStream  .Dispose ();
  oHttpWebResponse.Close   ();
  oHttpWebResponse.Dispose ();

对于调试,您可以通过查看Web请求的返回标头来查看接收到的数据。对于部分下载,您可能会获得例如

Content-Range: bytes 1000-2000/1156774
Content-Length: 1001

您从以下位置获取标题的键

oHttpWebResponse.Headers.Keys []

中的值
oHttpWebResponse.Headers []