使用C#下载一个Internet上的文件主要是依靠HttpWebRequest/HttpWebResonse和WebClient。具体处理起来还有同步和异步两种方式,所以我们其实有四种组合。

1、使用HttpWebRequest/HttpWebResonse和WebClient

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 
WebResponse response = request.GetResponse(); 
Stream stream = response.GetResponseStream();

if (!response.ContentType.ToLower().StartsWith("text/")) 

    //Value = SaveBinaryFile(response, FileName); 
    byte[] buffer = new byte[1024]; 
    Stream outStream = System.IO.File.Create(FileName); 
    Stream inStream = response.GetResponseStream();

int l; 
    do 
    { 
        l = inStream.Read(buffer, 0, buffer.Length); 
        if (l > 0) 
            outStream.Write(buffer, 0, l); 
    } 
    while (l > 0);

outStream.Close(); 
    inStream.Close(); 
}

2、使用WebClient

string url = "http://www.mozilla.org/images/feature-back-cnet.png"; 
WebClient myWebClient = new WebClient(); 
myWebClient.DownloadFile(url,"C:\\temp\\feature-back-cnet.png");

3、异步调用

异步调用可参见:http://wenku.baidu.com/view/f47cc781e53a580216fcfe64.html

最新文章

  1. 如何解决Maven和SBT下载Jar包太慢
  2. C#使用百度API通过IP获取地理位置和坐标
  3. unity5.3.4之no android module loaded
  4. 基于PHP生成静态页的实现方法
  5. 使用otl,报错:mysql Commands out of sync; you can't run this command now
  6. Epplus使用教程1(基本介绍)
  7. hdu------(4300)Clairewd’s message(kmp)
  8. Hadoop概述
  9. c++常见输入方法[持续更新]
  10. Jquery 之 日常积累(一)
  11. MediaPlayer简单使用,绑定surfaceView实现播放视频的功能
  12. Gentoo双网卡同时启用上内外网
  13. Centos sudo添加用户
  14. ACM 海贼王之伟大航路(深搜剪枝)
  15. SpringMVC参数绑定(从请求中接受参数)
  16. java关于字符串的一些实用操作工具类方法
  17. 工具方法 获取远程IP
  18. LineRenderer组建实现激光效果
  19. Eclipse导入Oracle/MySQL数库驱动包教程
  20. H5公共样式,用于所有H5开发页面

热门文章

  1. C#编程语言与面向对象——委托
  2. lambda表达式
  3. mySql中IFNULL的使用说明
  4. Android Studio使用教程-菜单(Edit)
  5. job history 的查看
  6. MySql 的常用优化
  7. 1月11日,HTML学习笔记
  8. (转)A Survival Guide to a PhD
  9. Disque
  10. 使用 ServiceStack.Text 序列化 json的实现代码【转】