How To Download Files In Xamarin.Forms

In this article, we will learn how to download any file from an online server and save it to the local directory of the Android and iOS Phones.

Xamarin

Platform Support

Here, we have used DependencyService to download any file from server path because we cannot download any file directly in Xamarin.Forms. We will see the DependencyService for Android and iOS Platforms. It is similar to UWP with slight changes.

DependencyService

Xamarin.Forms allows developers to define behavior in platform-specific projects. DependencyService then finds the right platform implementation, allowing shared code to access the native functionality. To know more about DependencyService Click Here.

Without much introduction, we will skip into the coding part of this article.

Steps

I have explained the method to create DependencyService with the steps as shown in the following.

  • Step 1: Creating new Xamarin.Forms Projects.
  • Step 2: Setting up AndroidManifest and info.plist
  • Step 3: Creating a Dependency Service for Android and iOS Platforms.
  • Step 4: Implementing the functionality to download the file in PCL.

Step 1 - Creating new Xamarin.Forms Projects

Create New Project by Selecting New - Project - Select Xamarin Cross-Platform App and click OK.

Xamarin

Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .NET Standard and click OK.

Xamarin

Step 2 - Setting up AndroidManifest and info.plist

Before starting, we need to make some setup respective to the Platforms.

For Android

  1. Expand your Android Project and open Properties.
  2. Then add or check the following permissions.
    • INTERNET
    • WRITE EXTERNAL STORAGE
  1. Then click Save.

For iOS

  1. Expand your iOS Project and Open your Info.plist file with XML Editor.
  2. Then add the following Permissions.
    1. <key>NSPhotoLibraryAddUsageDescription </key>  
    2. <string>Need permission to save files.</string>  
  • It provides permission to save file.
    1. <key>NSPhotoLibraryUsageDescription </key>  
    2. <string>Need permission to access files.</string>  
  • It provides permission to access files.

From iOS 11, Separate Permission Patterns are followed for saving and Accessing the Storage or Gallery.

Step 3 - Creating Dependency Service by Platform wise

In Xamarin.Forms, we need to go with dependency service to download files.

  1. First, we need to create an interface in your PCL or Shared Projects. In my case, I have created an Interface named  “IDownloader.cs”.
  2. Then Paste the following code in that.
    1. public interface IDownloader  
    2. {  
    3.     void DownloadFile(string url, string folder);  
    4.     event EventHandler<DownloadEventArgs> OnFileDownloaded;  
    5. }  
  1. Here, I have create a custom event handler to notify app users about file download. You have to create a class named DownloadEventArgsand paste the following code.
    1. public class DownloadEventArgs : EventArgs  
    2. {  
    3.     public bool FileSaved = false;  
    4.     public DownloadEventArgs(bool fileSaved)  
    5.     {  
    6.         FileSaved = fileSaved;  
    7.     }  
    8. }  

Xamarin

For Android

  1. Create a class named “AndroidDownloader.cs” in your Android Project and implement the class with “IDownloader” interface created in your Portable Library.
  2. We can use WebClient to download any file from the given URL. WebClient is used for both Android and iOS Platforms to download files.
  3. You can find the code used in Android Platform.
    1. public class AndroidDownloader : IDownloader  
    2. {  
    3.     public event EventHandler<DownloadEventArgs> OnFileDownloaded;  
    4.   
    5.     public void DownloadFile(string url, string folder)  
    6.     {  
    7.         string pathToNewFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, folder);  
    8.         Directory.CreateDirectory(pathToNewFolder);  
    9.   
    10.         try  
    11.         {  
    12.             WebClient webClient = new WebClient();  
    13.             webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);  
    14.             string pathToNewFile = Path.Combine(pathToNewFolder, Path.GetFileName(url));  
    15.             webClient.DownloadFileAsync(new Uri(url), pathToNewFile);  
    16.         }  
    17.         catch (Exception ex)  
    18.         {  
    19.             if (OnFileDownloaded != null)  
    20.                 OnFileDownloaded.Invoke(thisnew DownloadEventArgs(false));  
    21.         }  
    22.     }  
    23.   
    24.     private void Completed(object sender, AsyncCompletedEventArgs e)  
    25.     {  
    26.         if (e.Error != null)  
    27.         {  
    28.             if (OnFileDownloaded != null)  
    29.                 OnFileDownloaded.Invoke(thisnew DownloadEventArgs(false));  
    30.         }  
    31.         else  
    32.         {  
    33.             if (OnFileDownloaded != null)  
    34.                 OnFileDownloaded.Invoke(thisnew DownloadEventArgs(true));  
    35.         }  
    36.     }  
    37. }  
  1. Here, WebClient has an async event for notifying the download event completion.
  2. The Download event is notified by invoking the custom event created with Dependency Service from Android Platform code.

Xamarin

For iOS
  1. Create a class named “iOSDownloader.cs” in your iOS Project and implement the class with “IDownloader” interface created in your Portable Library.
  2. We can use WebClient to download any file from the given URL. WebClient is used for both Android and iOS Platforms to download files.
  3. You can find the code used in iOS Platform.
    1. public class IosDownloader : IDownloader  
    2. {  
    3.     public event EventHandler<DownloadEventArgs> OnFileDownloaded;  
    4.   
    5.     public void DownloadFile(string url, string folder)  
    6.     {  
    7.         string pathToNewFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), folder);  
    8.         Directory.CreateDirectory(pathToNewFolder);  
    9.   
    10.         try  
    11.         {  
    12.             WebClient webClient = new WebClient();  
    13.             webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);  
    14.             string pathToNewFile = Path.Combine(pathToNewFolder, Path.GetFileName(url));  
    15.             webClient.DownloadFileAsync(new Uri(url), pathToNewFile);  
    16.         }  
    17.         catch (Exception ex)  
    18.         {  
    19.             if (OnFileDownloaded != null)  
    20.                 OnFileDownloaded.Invoke(thisnew DownloadEventArgs(false));  
    21.         }  
    22.     }  
    23.   
    24.     private void Completed(object sender, AsyncCompletedEventArgs e)  
    25.     {  
    26.         if (e.Error != null)  
    27.         {  
    28.             if (OnFileDownloaded != null)  
    29.                 OnFileDownloaded.Invoke(thisnew DownloadEventArgs(false));  
    30.         }  
    31.         else  
    32.         {  
    33.             if (OnFileDownloaded != null)  
    34.                 OnFileDownloaded.Invoke(thisnew DownloadEventArgs(true));  
    35.         }  
    36.     }  
    37. }  
  1. Here, WebClient has an async event for notifying the download event completion.
  2. The Download event is notified by invoking the custom event created with Dependency Service from iOS Platform code.

    Xamarin

Don’t forget to add the following lines above the namespace of your Dependency Service classes.

[assembly: Dependency(typeof(Dependency_Class_Name))]

Step 4 - Implementing the functionality to download the file in PCL

The following code shows the following points

  • How to subscribe the download event.
  • How to call the download function.
  1. public partial class MainPage : ContentPage  
  2. {  
  3.     IDownloader downloader = DependencyService.Get<IDownloader>();  
  4.     public MainPage()  
  5.     {  
  6.         InitializeComponent();  
  7.         downloader.OnFileDownloaded += OnFileDownloaded;  
  8.     }  
  9.   
  10.     private void OnFileDownloaded(object sender, DownloadEventArgs e)  
  11.     {  
  12.         if (e.FileSaved)  
  13.         {  
  14.             DisplayAlert("XF Downloader""File Saved Successfully""Close");  
  15.         }  
  16.         else  
  17.         {  
  18.             DisplayAlert("XF Downloader""Error while saving the file""Close");  
  19.         }  
  20.     }  
  21.   
  22.     private void DownloadClicked(object sender, EventArgs e)  
  23.     {  
  24.         downloader.DownloadFile("http://www.dada-data.net/uploads/image/hausmann_abcd.jpg""XF_Downloads");  
  25.     }  
  26. }  

Download Code

You can download the full source code from GitHub. If you like this article, do like, share and star the repo in GitHub.