C# Programming > Data

C# Download File HTTP (WebRequest)

c# http download file

 

WebRequest and WebResponse Classes

It is becoming increasingly important for C#.Net applications to interact with the internet. Let's explore how to accomplish the most basic task, which is connecting to an URL to download a file or a webpage. There are several ways to accomplish the task with only C# source code, in this article we'll cover the simple HTTP connection.

The .Net Framework has a whole lot of internet-related classes built-in the System.Net namespace, making our life a lot easier. In this instance we need the WebRequest class and the WebResponse.

Connect to the URL

Connecting to the given URL, whether it is a page or a file you want to access, takes three lines of C# code:

WebRequest req = WebRequest.Create("[URL here]");
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();

By requesting a response from the URL the application will receive the same thing the browser will. Meaning it can be a page in html code, raw data if it is a file, and nothing if the URL does not exists.

For the purpose of this example we only need to worry about knowing when there is nothing there. Simply put everything inside a try-catch C# statement.

Download the File

The application is now ready to download a file. An easy way to download the data and keep track of how much was downloaded and how much there is to go is by doing it in chucks. For this programming example use 1 kb chucks. Here is the C# code:

byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);

The return value of the Read function will be how many bytes were downloaded from the stream. Thus if the number is 0, then the stream has finished downloading the URL. So if you put those lines on a while-loop and write the data up until the number read is 0, the application will download the entire file.

Make sure to add the following line somewhere inside the while-loop:

Application.DoEvents();

That line will ensure the C# application processes its events so it does not crash.

The Source Code

Download the example project files to view a full working C# application of the techniques described. Of interest is the fact that it is integrated with a progress bar...

Download C# HTTP URL Source Code

Back to C# Article List

License Agreement | Privacy Policy | Submit Link | Submit Article | Subscribe to Newsletter | Contact Us