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:

  1. C#使用SharpZipLib类库压缩、解压缩单个文件
  2. C#中的扩展方法
  3. 用C#得到访问IP出口的网卡
  4. c#中如何读取嵌入的资源
标签: ,
目前还没有任何评论.

Leave a Comment