Simple Web File Download


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.


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
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)
bytesRead += n;
bytesToRead -= n;
FileStream fstr =
new FileStream("weather.jpg", FileMode.OpenOrCreate,
fstr.Write(inBuf, 0, bytesRead);

Similar Articles