C#中http请求下载的常用方式demo
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中http请求下载的常用方式demo相关的知识,希望对你有一定的参考价值。
//通过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的主要内容,如果未能解决你的问题,请参考以下文章