Man*_*han 5 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;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 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 ();
Run Code Online (Sandbox Code Playgroud)
为了进行调试,您可以通过查看 Web 请求返回的标头来查看接收到的数据。对于部分下载,您可能会获得例如
Content-Range: bytes 1000-2000/1156774
Content-Length: 1001
Run Code Online (Sandbox Code Playgroud)
您可以从以下位置获取标头的密钥
oHttpWebResponse.Headers.Keys []
Run Code Online (Sandbox Code Playgroud)
以及来自的值
oHttpWebResponse.Headers []
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
119 次 |
最近记录: |