HTTP范围:使用WebClient C#的字节数

时间:2017-02-19 06:56:19

标签: c# http webclient

我正在尝试恢复文件下载。

我使用以下代码成功下载了我需要的文件。

    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类恢复的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

您的代码不起作用,因为您无法按照尝试设置它的方式设置Range标头。要验证是否只是订阅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 ---

好的,您可能需要自定义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

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);
}