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