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();
}
}
}
}
}
.Net实现文件下载Demo
最新推荐文章于 2024-04-24 18:21:45 发布