HttpWebRequest方式下载文件
2011年5月9日
分类: C#
就是使用HttpWebRequest和HttpWebResponse两个对象下载文件,很容易看懂。
/// <summary>
/// 下载文件并保存到本地目录。
/// </summary>
/// <param name="url"></param>
/// <param name="localPath"></param>
/// <param name="webProxy"></param>
/// <returns></returns>
public static bool DownloadFile(string url, string localPath, IWebProxy webProxy)
{
bool flag = false;
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
req.Proxy = webProxy;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
long totalBytes = resp.ContentLength;
using (Stream sResp = resp.GetResponseStream())
{
if (!Directory.Exists(localPath.Substring(0, localPath.LastIndexOf('\\'))))
{
Directory.CreateDirectory(localPath.Substring(0, localPath.LastIndexOf('\\')));
}
using (Stream sFile = new FileStream(localPath, FileMode.Create))
{
long totalDownloadBytes = 0;
byte[] bs = new byte[1024];
for (int size = sResp.Read(bs, 0, bs.Length); size > 0; size = sResp.Read(bs, 0, bs.Length))
{
totalDownloadBytes += size;
sFile.Write(bs, 0, size);
}
}
}
flag = true;
}
catch (Exception ex)
{
throw ex;
}
return flag;
}
原创文章,转载请注明: 转载自.NET开发者
本文链接地址: HttpWebRequest方式下载文件
文章的脚注信息由WordPress的wp-posturl插件自动生成
Related posts:
发表评论
| Trackback