HTTP 范围:WebClient C# 的字节数

HTTP Range: bytes with WebClient C#

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

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

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

您的代码不起作用,因为您无法按照您尝试设置的方式设置范围 header。要验证只需订阅 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 class 而不是 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);
}