Xamarin.Forms - Working With Files Using DependencyService

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means, reading and writing files is the easiest task using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute the data files with an app.

User-writable-storage can be implemented natively and then accessed using the DependencyService .

DependencyService

DependencyService allows the apps to call into platform-specific functionality from shared code. This functionality enables Xamarin.Forms apps to do anything that a native app can do.

DependencyService is a dependency resolver. In practice, an interface is defined and DependencyService finds the correct implementation of that interface from the various platform projects. 

Xamarin.Forms apps need three components to use DependencyService
  • Interface – The required functionality is defined by an interface in shared code.
  • Implementation Per Platform – Classes that implement the interface must be added to each platform project.
  • Registration – Each implementing class must be registered with DependencyService via a metadata attribute. Registration enables DependencyService to find the implementing class and supply it in place of the interface at runtime.
  • Call to DependencyService – Shared code needs to explicitly call DependencyService to ask for implementations of the interface.
The following image explains DependencyService.

Prerequisites
  • Visual Studio 2017(Windows or Mac)
    The steps given below are required to be followed in order to create a file using DependencyService in Xamarin.Forms, using Visual Studio.

  • Setting up a Xamarin.Forms Project
    Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.
Choose the Xamarin.Forms App project type under Cross-platform/App in the "New Project" dialog.

 
 
Name your app, select “Use Portable Class Library” for shared code, and target both - Android and iOS.

 
You probably want your project and solution to use the same name as your app. Put it in your preferred folder for projects and click "Create".

 

You now have a basic Xamarin.Forms app. Click the play button to try it out.

 

Creating Interface

Create an interface in Xamarin.Forms PCL. Go to Solution—>PCL—>Right click—>New—>Empty Class—>IFileReadWrite.cs.

 
 
Now, write the following code.

IFileReadWrite.cs
  1. using System;  
  2. using Xamarin.Forms;  
  3. namespace XamarinForms_Files {  
  4.     public interface IFileReadWrite {  
  5.         void WriteData(string fileName, string data);  
  6.         string ReadData(string filename);  
  7.     }  
  8. }  
 

Implementation per Platform

Android Implementation

Go to Solution—>Droid—>Right click—>New—>Empty Class—>FileHelper.cs.

 

Now, write the following code in this file.

FileHelper.cs
  1. using System;  
  2. using System.IO;  
  3. using Xamarin.Forms;  
  4. using XamarinForms_Files;  
  5. using XamarinForms_Files.Droid;  
  6. [assembly: Dependency(typeof(FileHelper))]  
  7. namespace XamarinForms_Files.Droid {  
  8.     public class FileHelper: IFileReadWrite {  
  9.         public void WriteData(string filename, string data) {  
  10.             var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);  
  11.             var filePath = Path.Combine(documentsPath, filename);  
  12.             File.WriteAllText(filePath, data);  
  13.         }  
  14.         public string ReadData(string filename) {  
  15.             var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);  
  16.             var filePath = Path.Combine(documentsPath, filename);  
  17.             return File.ReadAllText(filePath);  
  18.         }  
  19.     }  
  20. }  
 
iOS Implementation

Go to Solution—>iOS—>Right click—>New—>Empty Class—>FileHelper.cs. Now, write the following code.
 
 

FileHelper.cs
  1. using System;  
  2. using System.IO;  
  3. using Xamarin.Forms;  
  4. using XamarinForms_Files.iOS;  
  5. using XamarinForms_Files;  
  6. [assembly: Dependency(typeof(FileHelper))]  
  7. namespace XamarinForms_Files.iOS {  
  8.     public class FileHelper: IFileReadWrite {  
  9.         public void WriteData(string filename, string data) {  
  10.             var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);  
  11.             var filePath = Path.Combine(documentsPath, filename);  
  12.             File.WriteAllText(filePath, data);  
  13.         }  
  14.         public string ReadData(string filename) {  
  15.             var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);  
  16.             var filePath = Path.Combine(documentsPath, filename);  
  17.             return File.ReadAllText(filePath);  
  18.         }  
  19.     }  
  20. }  
For setting up the User Interface, go to MainPage.Xaml and write the following code.

MainPage.Xaml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:XamarinForms_Files" x:Class="XamarinForms_Files.XamarinForms_FilesPage">  
  3.     <StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="Center">  
  4.         <Entry x:Name="txtText" Placeholder="Write some text..."></Entry>  
  5.         <Button x:Name="btnWrite" Text="Write"></Button>  
  6.         <Button x:Name="btnRead" Text="Read"></Button>  
  7.         <Label x:Name="lblFileTexts" HorizontalTextAlignment="Center" LineBreakMode="WordWrap" Text="File Values:"></Label> </StackLayout>  
  8. </ContentPage>  
 
Call DependencyService

In this step, call DependencyService for your PCL.
  1. using Xamarin.Forms;  
  2. namespace XamarinForms_Files {  
  3.     public partial class XamarinForms_FilesPage: ContentPage {  
  4.         string fileName = "MyFile.txt";  
  5.         public XamarinForms_FilesPage() {  
  6.             InitializeComponent();  
  7.             btnWrite.Clicked += (sender, e) => {  
  8.                 string data = txtText.Text;  
  9.                 //Write data to Loal File using DependencyService  
  10.                 DependencyService.Get < IFileReadWrite > ().WriteData(fileName, data);  
  11.                 txtText.Text = string.Empty;  
  12.             };  
  13.             btnRead.Clicked += (sender, e) => {  
  14.                 //Read Loal File dat using DependencyService  
  15.                 string data = DependencyService.Get < IFileReadWrite > ().ReadData(fileName);  
  16.                 lblFileTexts.Text = data;  
  17.             };  
  18.         }  
  19.     }  
  20. }  
 
Click the play button to try it out.

 
 
I hope you will understand how to create a file using DependencyService.
 
 


Summary

This was the process of creating a file using DependencyService in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback.


Similar Articles