Microsoft & .NET.NETDownloading Files with the WebRequest and WebResponse Classes

Downloading Files with the WebRequest and WebResponse Classes

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

A few years ago I was being tasked with writing a console application that would download and save from the Web a file name that was passed to it via the command line. The application took me about 4 hours to write and involved a lot of Sockets programming and data conversion. With .NET, the WebRequest and WebResponse classes now reduce this task to about 5 minutes!

Here’s a simple function that you can easily plug into your C# application that will download a specified server file and save it to a local file. Instead of describing the function and then presenting it, the function contains comments that document exactly what is going on.

// Remember to add the following using statements to your code
// using System.Net;
// using System.IO;

public static int DownloadFile(String remoteFilename,
                               String localFilename)
{
  // Function will return the number of bytes processed
  // to the caller. Initialize to 0 here.
  int bytesProcessed = 0;

  // Assign values to these objects here so that they can
  // be referenced in the finally block
  Stream remoteStream  = null;
  Stream localStream   = null;
  WebResponse response = null;

  // Use a try/catch/finally block as both the WebRequest and Stream
  // classes throw exceptions upon error
  try
  {
    // Create a request for the specified remote file name
    WebRequest request = WebRequest.Create(remoteFilename);
    if (request != null)
    {
      // Send the request to the server and retrieve the
      // WebResponse object 
      response = request.GetResponse();
      if (response != null)
      {
        // Once the WebResponse object has been retrieved,
        // get the stream object associated with the response's data
        remoteStream = response.GetResponseStream();

        // Create the local file
        localStream = File.Create(localFilename);

        // Allocate a 1k buffer
        byte[] buffer = new byte[1024];
        int bytesRead;

        // Simple do/while loop to read from stream until
        // no bytes are returned
        do
        {
          // Read data (up to 1k) from the stream
          bytesRead = remoteStream.Read (buffer, 0, buffer.Length);

          // Write the data to the local file
          localStream.Write (buffer, 0, bytesRead);

          // Increment total bytes processed
          bytesProcessed += bytesRead;
        } while (bytesRead > 0);
      }
    }
  }
  catch(Exception e)
  {
    Console.WriteLine(e.Message);
  }
  finally
  {
    // Close the response and streams objects here 
    // to make sure they're closed even if an exception
    // is thrown at some point
    if (response     != null) response.Close();
    if (remoteStream != null) remoteStream.Close();
    if (localStream  != null) localStream.Close();
  }

  // Return total bytes processed to caller.
  return bytesProcessed;
}

Finally, here’s an example of using the DownloadFile function.

int read = DownloadFile("http://www.mysite.com/problem1.jpg",
                        "d:test.jpg");
Console.WriteLine("{0} bytes written", read);

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories