In a lot of apps you have the possibility to download files. Especially e-book reading apps or music apps use this very often. It’s a very useful feature. But, at the time of writing, there are not a lot of examples online that can help you with implementing this very useful feature. So here you have it, I tried to make it as easy as possible. If you have any questions, sound off in the comments below!

I’ll start with explaining the very basics, creating the Windows Phone project. Feel free to skip this part when you’re comfortable already with using Visual Studio.

The first thing you have to do is fire up Visual Studio. In case you don’t have Visual Studio installed, you can download the Express version over here for free. Make sure that you choose ‘Visual Studio for Windows’.

When you’ve done that, click on ‘New Project’, then you’ll get a Window like the one below, make sure that you choose Templates > Visual C# > Store Apps > Windows Phone Apps > Blank App (Windows Phone Silverlight). You can name it like you want, I’ll name it ‘TestWindowsPhone8DownloadFile’.

We’re going to start with the layout of the application. I’m going to put a big button at the top of the page that’ll let you download the file. It’ll look like this:

You can also just add a button, but make sure that the name of the button is ‘downloadBtn’. Now it’s time to start looking at the real code, the magic behind the user interface. First of all we’re going to implement some resources. Therefore add the following three lines to MainPage.xaml.cs.

1

2

3

using System.IO.IsolatedStorage;

using Windows.Storage;

using System.IO;

Now we can add some functionality to the button that we added on MainPage.xaml. When the button gets pressed we will initiate a WebClient that will download the file from the internet. When the download is completed the file will get stored and will be opened with the default application.

This is the code for downloadBtn_Click:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

privatevoiddownloadBtn_Click(objectsender,RoutedEventArgse)

{

try

{

//Create a webclient that'll handle your download

WebClient client=newWebClient();

//Run function when resource-read (OpenRead) operation is completed

client.OpenReadCompleted+=client_OpenReadCompleted;

//Start download / open stream

client.OpenReadAsync(newUri("http://www.education.gov.yk.ca/pdf/pdf-test.pdf"));//Use the url to your file instead, this is just a test file (pdf)