我正在尝试恢复文件下载。
我使用以下代码成功下载了我需要的文件。
downlaodfile = new WebClient();
// downlaodfile.Headers.Add("Range", "bytes=0-600000");
downlaodfile.DownloadFileAsync(new Uri(video.DownloadUrl), @"C:Videofile.pm4");
问题开始时,当我散发波纹管线时,我下载了0个字节
downlaodfile.Headers.Add("Range", "bytes=0-600000");
使用WebClient类恢复的正确方法是什么?
您的代码不起作用,因为您无法以尝试设置它的方式设置范围标题。要验证仅订阅DownloadFileCompleted
事件并转储错误:
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 ---
好吧,所以您可能需要一个自定义网络客户:
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
:
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);
}