码迷,mamicode.com
首页 > Windows程序 > 详细

C#中http请求下载的常用方式demo

时间:2016-01-31 21:05:51      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

//通过webClient方式

 

WebClient client = new WebClient();
string url="http://down6.3987.com:801/2010/office_3987.com.zip";
Stream strm = client.OpenRead("http://down6.3987.com:801/2010/office_3987.com.zip");
string filename=url.Substring(url.LastIndexOf(‘/‘)+1);
int count = 0;
byte[] buffer = new byte[4096];
FileStream fs = new FileStream(Application.StartupPath+"//"+filename, FileMode.Create);
while ((count = strm.Read(buffer, 0, buffer.Length)) > 0) {

fs.Write(buffer, 0, count);

}

fs.Close();
strm.Close();
strm.Dispose();
fs.Dispose();

 

//通过原生态HttpWebrequest方式

 

string url = "http://down6.3987.com:801/2010/office_3987.com.zip";
string filename = url.Substring(url.LastIndexOf(‘/‘) + 1);
//用webClient方式创建http请求
HttpWebRequest req =(HttpWebRequest)HttpWebRequest.Create(url) ; //创建链接

//获取服务其数据
HttpWebResponse res = (HttpWebResponse)req.GetResponse();

Stream mystream = res.GetResponseStream();

//开始文件操作
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory+"//"+filename, FileMode.Create, FileAccess.Write, FileShare.None);

byte[] buffer=new byte[1024];
int count=0;
while((count=mystream.Read(buffer,0,1024))>0)
{
fs.Write(buffer, 0, count);
}

fs.Close();
mystream.Close();
fs.Dispose();

C#中http请求下载的常用方式demo

标签:

原文地址:http://www.cnblogs.com/wuhanly/p/5173539.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!