日期:2014-05-18  浏览次数:20747 次

HttpWebRequest下载文件问题,如何保存成为二进制文件?
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 是网站上的一个压缩包。

------解决方案--------------------
while (numBytesToRead > 0) 整块换成下面代码
C# code
int len = 0;
while ((len = receiveStream.Read(buffer, 0, buffer.Length)) > 0)
{
    fs.Write(buffer, 0, len);
}

------解决方案--------------------
如果只是下载二进制流,使用简单的一句 new WebClient().DownloadData就行了。