.Net实现文件下载Demo

来源:互联网 发布:网络项目70000元 编辑:程序博客网 时间:2024/05/21 23:59
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();                }            }        }    }}

1 0
原创粉丝点击