gpt4 book ai didi

c# - 在 C# WPF 中恢复下载

转载 作者:太空狗 更新时间:2023-10-29 23:49:06 26 4
gpt4 key购买 nike

我正在开发一个 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;
}
}

最佳答案

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

  // 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 ();

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

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

您从中获取 header 的键

oHttpWebResponse.Headers.Keys []

以及来自

的值
oHttpWebResponse.Headers []

关于c# - 在 C# WPF 中恢复下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54026499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com