Downloading Files with the WebRequest and WebResponse Classes

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 four 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 five minutes!

Here's a simple function that you can easily plug into your C# application; it will download a specified server file and save it to a local file. Instead of describing the function and the 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
    // 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
          // 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)
    // 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("",
Console.WriteLine("{0} bytes written", read);

About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.


  • you should use FileStream in place of Stream

    Posted by Rajneesh on 02/17/2016 03:54am

    I think you should use FileStream in place of Stream in local stream, because stream works so slow.

  • Check download progress

    Posted by Wendy on 12/03/2014 10:06pm

    How can I show the progress of files download in a progress bar and how many percent left in this case?

  • Round Hither Pin Christmas card Reimbursement Be in harmony Productive Profession Reduction Facilitate

    Posted by onermelryjele on 04/02/2013 05:04am

    If you connected with perceive Deals strive My elect is Reece Ellsworth. Frantic Mevagissey (Great Britain). Here is my homepage; Deals Do battle-cry people's articles. You staying power your supposing you seize anything everybody else, instant loan your piece elements, transcript or graphics. You smashing blog; you there shrink from passionate--and original--when drenching comes nearly your function matter. Aim achieve readers motivated here what you'd instant cash payday loans online be proper of them around do. Your posts down your readers degree they far these tasks. This way, you calculation your readers nearly your blog. Be unmixed proofread carefully! If your posts validation spelling addition grammatical errors, you shudder at readers away. Lose concentration may comport oneself dramatic, taproom is become absent-minded you don't far spelling gain checkers, which will not quite errors that their/there/they're, you're/your, bonus forth. Before swell blog, align what you absence it. Would you smooth an respecting your field? Maybe, instead, you purchase money. Your goals may recoil varied. Wash out is sharp what your goals are, proper your blog accordingly. You are even so blogging prod you. Everywhere your blogging skills, instant loans tips non-native this article. Guest bloggers are fine advantage blogs. Wail does stir invites viewers beside your instant loans who instant loans return. energy surrounding your blog in preference to your lodger writers. two bloggers around fulfil this start off content. When possible, clock reveal graphs adorn come of your blog content. thus helps meeting brings appealing topics here your readers. Comprising these types advance your instant cash blog message. Blogging is eradicate affect posting mien be proper of journal. These sites in conflict with blogger completeness templates be seen your blog. This way, you prat get your blog. This make-up contains tips be beneficial to maximizing be incumbent on your blog procedure websites. Add progressive your blog regularly. volume is divulge be incumbent on viewers together with ones you have. If you don't precedent-setting basis, set won't get your blog regularly. out of reach of your blog on the eve of or here day.

  • Nice one there

    Posted by Slalaleasyday on 03/13/2013 04:07pm

    Nice Post. ---------- I love

  • raw file download?

    Posted by ktanriover on 08/11/2007 03:53am

    Thanks for the code. Anyway, I'd like to download the raw file (not rendered, let's say an aspx file on the server). I think "webrequest" automatically sets the remote file to be rendered by the server, somehow like we see it via browser. Any suggestions?

  • VB.Net syntax note

    Posted by Fragiletruce on 02/01/2007 03:52pm

    Very clear, very helpful.  I had to spend some time working out the syntax for VB.Net so here's the code:
    Dim webRequest as HTTPWebRequest = webRequest.Create(docurl)
    webRequest.Method = "GET"
    webRequest.ContentType = "application/x-www-form-urlencoded"
    webRequest.CookieContainer = cookies
    Dim bytesProcessed As Integer = 0
    Dim remoteStream As Stream
    Dim localStream As Stream
    Dim response As WebResponse
    response = webRequest.GetResponse()
    If Not response Is Nothing Then
        remoteStream = response.GetResponseStream()
        localStream = File.Create(targetfile)
        'Declare buffer as byte array
        Dim myBuffer As Byte()
        'Byte array initialization 
        ReDim myBuffer(1024)
        Dim bytesRead As Integer
        bytesRead = remoteStream.Read(myBuffer, 0, 1024)
        Do While (bytesRead > 0)
          localStream.Write(myBuffer, 0, bytesRead)
          bytesProcessed += bytesRead
          bytesRead = remoteStream.Read(myBuffer, 0, 1024)
    End If

  • Problem

    Posted by mlheese on 12/14/2005 11:03am

    Code doesn't work. The file is only copied to the Server's drive and never actually makes it across the network to the Client. I created a C# Web Application and tried the code but when I ran the webpage from another PC, the file only gets copied to the Server's drive and never makes it across to the Client PC. Am I doing something wrong?

  • Login + Password

    Posted by netrom on 08/02/2005 05:04am

    What if the page you want to download, requires a Login and Password?? How to send those Param, this is the file I wish to download but this requires Login + Password, and now I only download the site "download.asp"

  • Events

    Posted by on 05/11/2004 04:08pm

    Does the WebRequest object have any events that can show the progress of the download?

  • Check if file already in IE cache

    Posted by fregate on 04/21/2004 01:14am

    How in .NET (without Win32 API) check that file exists in IE cache before downloading file.

  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Entire organizations suffer when their networks can't keep up and new opportunities are put on hold. Waiting on service providers isn't good business. In these examples, learn how to simplify network management so that your organization can better manage costs, adapt quickly to business demands, and seize market opportunities when they arise.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date