C# Programming > Web

C# Download File HTTP (WebRequest)

c# http download file

 

WebRequest and WebResponse

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 a URL to download data, whether it'd be a file or a webpage. There are several ways to accomplish the task with only C# code, in this article we'll cover the simple HTTP connection.

The .NET Framework comes with ample support for online operations with the System.Net namespace. In this instance we will use the WebRequest and WebResponse .NET classes.

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();

The resulting stream behaves very much like a regular IO stream in .NET desktop applications. The data will be downloaded in raw bytes and it is up to the developer to interpret the data correctly with classes from the System.IO namespace.

For example, if we are downloading a zip file, the stream might be written directly out to a file. If on the other hand, the URL was for a webpage (eg. html or php page), then we can use a StreamReader to read the entire stream as a string.

When working with streams is important to keep in mind to always close and dipose a stream when a section of code is done with it. This can save you a lot of time trying to track down bugs and errors later.

So what happens if the URL doesn't exist? Or if the computer in which the application is running is not connected to the internet? Luckily these scanarios are handled by the WebRequest and WebResponse classes, which throw an exception depending on the situation.

For example, the WebRequest class will throw a WebException on the GetResponse call if there is no internet connection or if there is no response from the server (technically both are the same thing).

On the other hand, the stream will throw an exception if the connection dies in the middle for some reason.

Wrapping the logic in a try-catch statement can produce a smooth experience for the user:

try
{
     WebRequest req = WebRequest.Create("[URL here]");
     WebResponse response = req.GetResponse();
     Stream stream = response.GetResponseStream();
     //...
}
catch (Exception)
{
     MessageBox.Show("There was a problem downloading the file");
}

Page 2
Keeping Track of Download Progress >>

 

Back to C# Article List