问题描述
我正在尝试恢复文件下载.
I am trying to resume file download.
我使用以下代码成功下载所需的文件.
I use the below code to successfully download the file I need.
downlaodfile = new WebClient();
// downlaodfile.Headers.Add("Range", "bytes=0-600000");
downlaodfile.DownloadFileAsync(new Uri(video.DownloadUrl), @"C:\Videofile.pm4");
当我取消注释以下行时,问题就开始了,我下载了0个字节
The problem start when I uncomment the bellow line I get 0 bytes downloaded
downlaodfile.Headers.Add("Range", "bytes=0-600000");
使用WebClient类恢复的正确方法是什么?
What is the right way to resume with WebClient class?
推荐答案
您的代码不起作用,因为您无法以尝试设置的方式设置Range标头.要验证是否只需订阅 DownloadFileCompleted
事件并转储错误:
Your code doesn't work because you cannot set the Range header the way you are trying to set it. To verify that simply subscribe to the DownloadFileCompleted
event and dump the error:
downlaodfile.DownloadFileCompleted += (sender, e) =>
{
Console.WriteLine(e.Error);
};
您将得到打印:
System.Net.WebException: An exception occurred during a WebClient request. ---> System.ArgumentException: The 'Range' header must be modified using the appropriate property or method.
Parameter name: name
at System.Net.WebHeaderCollection.ThrowOnRestrictedHeader(String headerName)
at System.Net.WebHeaderCollection.Add(String name, String value)
at System.Net.HttpWebRequest.set_Headers(WebHeaderCollection value)
at System.Net.WebClient.CopyHeadersTo(WebRequest request)
at System.Net.WebClient.GetWebRequest(Uri address)
at System.Net.WebClient.DownloadFileAsync(Uri address, String fileName, Object userToken)
--- End of inner exception stack trace ---
确定,因此您可能需要自定义WebClient:
OK, so you might need a custom WebClient:
public class WebClientEx : WebClient
{
private readonly long from;
private readonly long to;
public WebClientEx(long from, long to)
{
this.from = from;
this.to = to;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
request.AddRange(this.from, this.to);
return request;
}
}
您可以这样使用:
downlaodfile = new WebClientEx(0, 600000);
downlaodfile.DownloadFileAsync(new Uri(video.DownloadUrl), @"C:\Videofile.pm4");
或仅使用 HttpWebRequest
类而不是 WebClient
:
var request = (HttpWebRequest)WebRequest.Create(video.DownloadUrl);
request.AddRange(0, 600000);
using (var response = await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var output = File.Create(@"C:\Videofile.pm4"))
{
await stream.CopyToAsync(output);
}
,或者如果您愿意使用 HttpClient
:
or if you prefer with an HttpClient
:
var client = new HttpClient();
client.DefaultRequestHeaders.Range = new RangeHeaderValue(0, 600000);
using (var stream = await client.GetStreamAsync(video.DownloadUrl))
using (var output = File.Create(@"C:\Videofile.pm4"))
{
await stream.CopyToAsync(output);
}
这篇关于HTTP范围:WebClient C#的字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!