HttpWebRequest下载文件问题,如何保存成为二进制文件?

不懂必须要问 2012-06-13 05:40:44
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for the response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Gets the stream associated with the response.
Stream receiveStream = myHttpWebResponse.GetResponseStream();

byte[] buffer = new byte[1024];
int numBytesToRead = (int)myHttpWebResponse.ContentLength;
int numBytesRead = 0;
FileStream fs = new FileStream(System.Environment.CurrentDirectory + "\\"+url.Substring(url.LastIndexOf("/"), url.Length - url.LastIndexOf("/")), FileMode.Create);
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = receiveStream.Read(buffer, numBytesRead, 1024);
// The end of the file is reached.
if (n == 0)
break;
fs.Write(buffer, numBytesRead, buffer.Length);
numBytesRead += n;
numBytesToRead -= n;
}
fs.Flush();
fs.Close();
fs.Dispose();
receiveStream.Close();



ulr 是网站上的一个压缩包。
...全文
322 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
不懂必须要问 2012-06-13
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

如果只是下载二进制流,使用简单的一句 new WebClient().DownloadData就行了。
[/Quote]

傻了!这个真够精简好用。
  • 打赏
  • 举报
回复
如果只是下载二进制流,使用简单的一句 new WebClient().DownloadData就行了。
孟子E章 2012-06-13
  • 打赏
  • 举报
回复
http://dotnet.aspx.cc/file/HttpWebRequest-Download-Http-Url.aspx

使用 HttpWebRequest 下载任意类型的文件
__天涯寻梦 2012-06-13
  • 打赏
  • 举报
回复
while (numBytesToRead > 0) 整块换成下面代码
int len = 0;
while ((len = receiveStream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, len);
}

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧