C#下载文件,断点下载Demo

  using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        private static void DownloadFile(Action progressAction
            ,Action exceptionAction,Action okAction = null)
        {
            try
            {
                var request = WebRequest
                    .CreateHttp("http://mytianh5.oss-cn-beijing.aliyuncs.com/website/video/zaojiaoji.mp4");
                if (File.Exists("zaojiaoji.mp4"))
                {
                    using var fileStream = File.OpenRead("zaojiaoji.mp4");
                    request.Headers[HttpRequestHeader.Range]
                        = $"bytes={fileStream.Length}-";
                }
                if (request.GetResponse() is HttpWebResponse response
                    && (HttpStatusCode.OK == response.StatusCode
                        || HttpStatusCode.PartialContent == response.StatusCode))
                {
                    using (response)
                    {
                        using var responseStream = response.GetResponseStream();
                        using var fileStream = File.Open("zaojiaoji.mp4"
                            , HttpStatusCode.PartialContent == response.StatusCode ? FileMode.Append
                            : File.Exists("zaojiaoji.mp4") ? FileMode.Truncate : FileMode.Create);
                        var count = 0L;
                        if (HttpStatusCode.PartialContent == response.StatusCode)
                        {
                            count += fileStream.Length;
                        }
                        var max = count + response.ContentLength;
                        var buffer = new byte[1024 * 2];
                        var readBytes = 0;
                        while (responseStream != null
                               && (readBytes = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fileStream.Write(buffer, 0, readBytes);
                            count += readBytes;
                            progressAction?.Invoke(count
                                ,max);
                        }
                        okAction?.Invoke();
                    }
                }
                else
                {
                    exceptionAction?.Invoke(new Exception("error"));
                }
            }
            catch(Exception e)
            {
                exceptionAction?.Invoke(e);
            }
        }


        private static void Main(string[] args)
        {
            DownloadFile(delegate(long l, long l1)
            {
                Console.Write("=");
            },Console.WriteLine);
        }
    }
}

你可能感兴趣的:(C#下载文件,断点下载Demo)