• C# 使用HTTP下载文件,支持续传


    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    
    namespace Flames.Utils.Net
    {
        public class Http
        {
    
            /// <summary>
            /// 下载进度
            /// </summary>
            public event Action<int> ShowDownloadPercent;
    
            /// <summary>
            /// 一次下载量
            /// </summary>
            private int ByteSize = 1000000;
    
            /// <summary>
            /// 下载中的后缀,下载完成去掉
            /// </summary>
            private const string Suffix = ".downloading";
    
            /// <summary>
            /// Http方式下载文件
            /// </summary>
            /// <param name="url">http地址</param>
            /// <param name="localfile">本地文件</param>
            /// <returns></returns>
            public int DownloadFile(string url, string localfile)
            {
                int ret = 0;
                string localfileReal = localfile;
                string localfileWithSuffix = localfileReal + Suffix;
    
                try
                {
                    long startPosition = 0;
                    FileStream writeStream = null;
    
                    if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(localfileReal)) return 1;
    
                    if (File.Exists(localfileReal)) return 0;
    
                    //取得远程文件长度
                    long remoteFileLength = GetHttpLength(url);
    
                    if (remoteFileLength == 0) return 2;
    
                    //判断要下载的文件是否存在
                    if (File.Exists(localfileWithSuffix))
                    {
                        writeStream = File.OpenWrite(localfileWithSuffix);
                        startPosition = writeStream.Length;
                        if (startPosition > remoteFileLength)
                        {
                            writeStream.Close();
                            File.Delete(localfileWithSuffix);
                            writeStream = new FileStream(localfileWithSuffix, FileMode.Create);
                        }
                        else if (startPosition == remoteFileLength)
                        {
                            DownloadFileOk(localfileReal, localfileWithSuffix);
                            writeStream.Close();
                            return 0;
                        }
                        else
                        {
                            writeStream.Seek(startPosition, SeekOrigin.Begin);
                        }
                    }
                    else
                    {
                        writeStream = new FileStream(localfileWithSuffix, FileMode.Create);
                    }
    
                    HttpWebRequest req = null;
                    HttpWebResponse rsp = null;
                    try
                    {
                        req = (HttpWebRequest)HttpWebRequest.Create(url);
                        if (startPosition > 0) req.AddRange((int)startPosition);
                        
                        rsp = (HttpWebResponse)req.GetResponse();
                        using (Stream readStream = rsp.GetResponseStream())
                        {
                            byte[] btArray = new byte[ByteSize];
                            long currPostion = startPosition;
                            int contentSize = 0;
                            while ((contentSize = readStream.Read(btArray, 0, btArray.Length)) > 0)
                            {
                                writeStream.Write(btArray, 0, contentSize);
                                currPostion += contentSize;
    
                                ShowDownloadPercent?.Invoke((int)(currPostion * 100 / remoteFileLength));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ret = 3;
                    }
                    finally
                    {
                        if (writeStream != null)
                            writeStream.Close();
                        if (rsp != null)
                            rsp.Close();
                        if (req != null)
                            req.Abort();
    
                        if (ret == 0)
                            DownloadFileOk(localfileReal, localfileWithSuffix);
                    }
                }
                catch (Exception ex)
                {
                    //Log.Info("获取远程文件失败!exception:
    " + ex.ToString());
                    ret = 4;
                }
    
                return ret;
            }
    
            /// <summary>
            /// 下载完成
            /// </summary>
            private void DownloadFileOk(string localfileReal, string localfileWithSuffix)
            {
                try
                {
                    //去掉.downloading后缀
                    FileInfo fi = new FileInfo(localfileWithSuffix);
                    fi.MoveTo(localfileReal);
                }
                catch (Exception ex)
                {
    
                }
                finally
                {
                    //通知完成
                    if (ShowDownloadPercent != null)
                        ShowDownloadPercent(100);
                }
            }
    
            // 从文件头得到远程文件的长度
            private long GetHttpLength(string url)
            {
                long length = 0;
                HttpWebRequest req = null;
                HttpWebResponse rsp = null;
                try
                {
                    req = (HttpWebRequest)HttpWebRequest.Create(url);
                    rsp = (HttpWebResponse)req.GetResponse();
                    if (rsp.StatusCode == HttpStatusCode.OK)
                        length = rsp.ContentLength;
                }
                catch (Exception ex)
                {
    
                }
                finally
                {
                    if (rsp != null)
                        rsp.Close();
                    if (req != null)
                        req.Abort();
                }
    
                return length;
            }
        }
    }
    
    
  • 相关阅读:
    好文!悟透JavaScript
    关于“四舍六入五成双/四舍六入五留双/四舍六入五单双”等口诀的实例研究
    第四个:怎么应付在背地里说你坏话的人
    为什么日全食时开始下雨,10分钟后雨又停了。初中物理知识。
    吃萝卜去口气(口臭)
    今天12点34分56秒是一个神奇的时刻
    sharepoint2010人性化的地方员工离职AD账号禁用(个人网站自动提醒上级经理功能)
    指定为添加到网站中的项目显示“新”图标的天数。
    解决sharepoint2010的多行文本框的插入图片—【从sharepoint】的disabled问题
    sharepoint2010的IE6不支持的解决方法
  • 原文地址:https://www.cnblogs.com/flamegreat/p/14620733.html
Copyright © 2020-2023  润新知