Reader Level:
ARTICLE

Simple Web File Download

Posted by Bill Farley Articles | Internet & Web March 23, 2001
This is a simple program that shows how to download files from the web and save them. The program uses the HttpWebRequest and HttpWebResponse classes to request and retrieve the requested file.
  • 0
  • 0
  • 36881

Description:

This is a simple program that shows how to download files from the web and save them. The program uses the HttpWebRequest and HttpWebResponse classes to request and retrieve the requested file. The data are read into a buffer. A FileStream class is used to save the file to disk. In this example, a doppler radar map that covers the area I live is requested and saved to a file called "weather.jpg". Since the data are downloaded and read into the buffer asynchronously, a loop is required to read and keep track of how many bytes have been read, and the point in the stream where the next read should start. The loop will continue until the buffer is full or 0 bytes are read, indicating the end of the stream has been reached. The buffer must be sized large enough to hold the file. This is not a problem in this case as the doppler jpg's are a standard and known size.

Requirement:

Requires .NET SDK

How To Compile?

csc /r:System.Net.dll /r:System.IO.dll webretrieve.cs 

Source Code

using System.IO;
using System.Net;
using System.Text;
class WebRetrieve
{
public static void Main()
{
HttpWebRequest wr = (HttpWebRequest)WebRequestFactory.Create
(http://maps.weather.com/web/radar/us_orl_ultraradar_large_usen.jpg);
HttpWebResponse ws = (HttpWebResponse)wr.GetResponse();
Stream str = ws.GetResponseStream();
byte[] inBuf = new byte[100000];
int bytesToRead = (int) inBuf.Length;
int bytesRead = 0;
while (bytesToRead > 0)
{
int n = str.Read(inBuf, bytesRead,bytesToRead);
if (n==0)
break;
bytesRead += n;
bytesToRead -= n;
}
FileStream fstr =
new FileStream("weather.jpg", FileMode.OpenOrCreate,
FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
str.Close();
fstr.Close();
}

Article Extensions
Contents added by dinesh mali on Aug 03, 2009
COMMENT USING

Trending up