.Net实现文件下载Demo

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

namespace downlown
{
    public class DownLoadDemo
    {
        /// <summary>
        /// request访问方式,默认GET
        /// </summary>
        public string Method { get; set; }

        /// <summary>
        /// request过期时间(不能为0)
        /// </summary>
        public int Timeout { get; set; }

        /// <summary>
        /// 资源url(必需)
        /// </summary>
        public string url { get; set; }

        /// <summary>
        /// 下载到本地的路径(必需)
        /// </summary>
        public string path { get; set; }

        public DownLoadDemo()
        {
            this.Method = "GET";
            this.Timeout = 12000;
        }

        public DownLoadDemo(string url, string path) : this()
        {
            this.url = url;
            this.path = path;
        }

        protected HttpWebRequest CreateRequest()
        {
            if (url == null)
            {
                throw new Exception("url为非法输入!");
            }
            HttpWebRequest request = WebRequest.Create(this.url) as HttpWebRequest;
            request.Method = this.Method;
            request.Timeout = this.Timeout;
            return request;
        }

        public void DownLoad()
        {
            Stream stream = null;
            FileStream fs = null;
            HttpWebRequest request = CreateRequest();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            try
            {
                int length = 2048;
                byte[] buffer = new byte[length];
                stream = response.GetResponseStream();
                fs = new FileStream(path, FileMode.Create, FileAccess.Write);
                while (stream.Read(buffer, 0, length) > 0)
                {
                    fs.Write(buffer, 0, length);
                }
            }
            catch (Exception ex)
            {
                // do something
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值