Background File Downloader For Windows 10

Background transfer is used for long-term transfer or download operations such as video, music, and images. For that time user will allow play around your app don’t stop the user to wait.

BackgroundDownloader class will help you to transfer or download the files from the server event the app is running in foreground. If the user exits the app, the download will continue in the background. You can check when the app is relaunched.

Let’s see the steps how to download files from server.

Create new Windows 10 project and give a suitable name.

Design your xaml page. Here I will create one textbox to enter your download url then textblock for showing the status and one button to start the download.

XAML Code

  1. <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  2.     <Grid.RowDefinitions>  
  3.         <RowDefinition Height="Auto"></RowDefinition>  
  4.         <RowDefinition Height="Auto"></RowDefinition>  
  5.         <RowDefinition Height="Auto"></RowDefinition>  
  6.         <RowDefinition Height="Auto"></RowDefinition>  
  7.     </Grid.RowDefinitions>  
  8.     <TextBox x:Name="linkBox" Height="20" Width="200" Grid.Row="0" HorizontalAlignment="Left"></TextBox>  
  9.     <TextBlock x:Name="Statustext" Height="30" Grid.Row="1" HorizontalAlignment="Center" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" />  
  10.     <Button x:Name="downloadBtn" Height="30" Grid.Row="2" Content="Download" Click="downloadBtn_Click" HorizontalAlignment="Center" VerticalAlignment="Top" /> </Grid>  
Next we need to ensure that your app has the capability to access the internet. To enable the capability follow the below steps.

Double click your package.aapmainfest file in you solution explorer and enable the internet client like the following screen.

package

Next go to code behind page and write the following code.
  1. DownloadOperation downloadOperation;  
  2. CancellationTokenSource cancellationToken;  
  3. Windows.Networking.BackgroundTransfer.BackgroundDownloader backgroundDownloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();  
  4. public MainPage()  
  5. {  
  6.     this.InitializeComponent();  
  7. }  
  8. public async void Download()  
  9. {  
  10.     FolderPicker folderPicker = new FolderPicker();  
  11.     folderPicker.SuggestedStartLocation = PickerLocationId.Downloads;  
  12.     folderPicker.ViewMode = PickerViewMode.Thumbnail;  
  13.     folderPicker.FileTypeFilter.Add("*");  
  14.     StorageFolder folder = await folderPicker.PickSingleFolderAsync();  
  15.     if (folder != null)  
  16.     {  
  17.         StorageFile file = await folder.CreateFileAsync("NewFile.jpg", CreationCollisionOption.GenerateUniqueName);  
  18.         Uri durl = new Uri(linkBox.Text.ToString());  
  19.         downloadOperation = backgroundDownloader.CreateDownload(durl, file);  
  20.         Progress < DownloadOperation > progress = new Progress < DownloadOperation > (progressChanged);  
  21.         cancellationToken = new CancellationTokenSource();  
  22.         try  
  23.         {  
  24.             Statustext.Text = "Initializing...";  
  25.             await downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress);  
  26.         }  
  27.         catch (TaskCanceledException)  
  28.         {  
  29.             downloadOperation.ResultFile.DeleteAsync();  
  30.             downloadOperation = null;  
  31.         }  
  32.     }  
  33. }  
  34. private void progressChanged(DownloadOperation downloadOperation)  
  35. {  
  36.     int progress = (int)(100 * ((double) downloadOperation.Progress.BytesReceived / (double) downloadOperation.Progress.TotalBytesToReceive));  
  37.     Statustext.Text = String.Format("{0} of {1} kb. downloaded - %{2} complete.", downloadOperation.Progress.BytesReceived / 1024, downloadOperation.Progress.TotalBytesToReceive / 1024, progress);  
  38.     switch (downloadOperation.Progress.Status)  
  39.     {  
  40.         case BackgroundTransferStatus.Running:  
  41.             {  
  42.                 break;  
  43.             }  
  44.         case BackgroundTransferStatus.PausedByApplication:  
  45.             {  
  46.                 break;  
  47.             }  
  48.         case BackgroundTransferStatus.PausedCostedNetwork:  
  49.             {  
  50.                 break;  
  51.             }  
  52.         case BackgroundTransferStatus.PausedNoNetwork:  
  53.             {  
  54.                 break;  
  55.             }  
  56.         case BackgroundTransferStatus.Error:  
  57.             {  
  58.                 Statustext.Text = "An error occured while downloading.";  
  59.                 break;  
  60.             }  
  61.     }  
  62.     if (progress >= 100)  
  63.     {  
  64.         downloadOperation = null;  
  65.     }  
  66. }  
  67. private void downloadBtn_Click(object sender, RoutedEventArgs e)  
  68. {  
  69.     Download();  
  70. }  
  71. }  
Created a new DownloadOperation and CancellationTokenSource object using the BackgroundDownloader class when passed the required StorageFile location and download URI values and call the CreateDownload method to download the file.

In the above code user first select the location to store the file and start the download and register a method to receive progress updates.

Progress class helps you to track the downloading progress and you can get  how much bytes received.

Now run the app and see the output like the following screen. Here I am going to download the google logo.

For source code

textblock

textblock