是否可以从WebClient c#覆盖DownloadFileAsync而不覆盖/替换下载的文件?

时间:2017-06-11 04:53:33

标签: c# webclient downloadfileasync

我的目标是在从最新的写入字节开始暂停下载后继续下载某个文件,而不是从0开始。 我已经将 addRange标头添加到我的自定义类中(按预期工作)但默认情况下,DownloadFileAsync会覆盖我下载的文件,从而从头开始创建。

这是我的自定义课程:

public class CookieAwareWebClient : WebClient
{
    private class CookieContainer
    {
        Dictionary<string, string> _cookies;

        public string this[Uri url]
        {
            get
            {
                if (_cookies.TryGetValue(url.Host, out string cookie))
                    return cookie;

                return null;
            }
            set
            {
                _cookies[url.Host] = value;
            }
        }

        public CookieContainer()
        {
            _cookies = new Dictionary<string, string>();
        }
    }

    private CookieContainer cookies;

    private readonly long from;
    private readonly long to;

    public CookieAwareWebClient(long from, long to) : base()
    {
        cookies = new CookieContainer();
        this.from = from;
        this.to = to;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);

        if (request is HttpWebRequest)
        {
            string cookie = cookies[address];
            if (cookie != null)
                ((HttpWebRequest)request).Headers.Set("cookie", cookie);

            if (from != 0 || to != 0)
            {
                ((HttpWebRequest)request).AddRange(from, to);
            }
        }

        return request;
    }

    protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
    {
        WebResponse response = base.GetWebResponse(request, result);

        string[] cookies = response.Headers.GetValues("Set-Cookie");
        if (cookies != null && cookies.Length > 0)
        {
            string cookie = "";
            foreach (string c in cookies)
                cookie += c;

            this.cookies[response.ResponseUri] = cookie;
        }

        return response;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        WebResponse response = base.GetWebResponse(request);

        string[] cookies = response.Headers.GetValues("Set-Cookie");
        if (cookies != null && cookies.Length > 0)
        {
            string cookie = "";
            foreach (string c in cookies)
                cookie += c;

            this.cookies[response.ResponseUri] = cookie;
        }

        return response;
    }
}

1 个答案:

答案 0 :(得分:0)

DownloadFileAsync不是虚拟的,因此您无法覆盖它。

WebClient.DownloadFileAsync方法是从网络位置下载文件的便捷方式,它只接受URL和本地路径并完成工作。暂停和恢复的要求不在此API的范围内,您必须编写一些代码以从响应流中读取,并写入文件流(在Append模式下从现有文件打开)。