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
- using System;
- using Xamarin.Forms;
- namespace XamarinForms_Files {
- public interface IFileReadWrite {
- void WriteData(string fileName, string data);
- string ReadData(string filename);
- }
- }
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
- using System;
- using System.IO;
- using Xamarin.Forms;
- using XamarinForms_Files;
- using XamarinForms_Files.Droid;
- [assembly: Dependency(typeof(FileHelper))]
- namespace XamarinForms_Files.Droid {
- public class FileHelper: IFileReadWrite {
- public void WriteData(string filename, string data) {
- var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
- var filePath = Path.Combine(documentsPath, filename);
- File.WriteAllText(filePath, data);
- }
- public string ReadData(string filename) {
- var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
- var filePath = Path.Combine(documentsPath, filename);
- return File.ReadAllText(filePath);
- }
- }
- }
iOS Implementation
Go to Solution—>iOS—>Right click—>New—>Empty Class—>FileHelper.cs. Now, write the following code.
FileHelper.cs
- using System;
- using System.IO;
- using Xamarin.Forms;
- using XamarinForms_Files.iOS;
- using XamarinForms_Files;
- [assembly: Dependency(typeof(FileHelper))]
- namespace XamarinForms_Files.iOS {
- public class FileHelper: IFileReadWrite {
- public void WriteData(string filename, string data) {
- var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
- var filePath = Path.Combine(documentsPath, filename);
- File.WriteAllText(filePath, data);
- }
- public string ReadData(string filename) {
- var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
- var filePath = Path.Combine(documentsPath, filename);
- return File.ReadAllText(filePath);
- }
- }
- }
For setting up the User Interface, go to MainPage.Xaml and write the following code.
MainPage.Xaml
- <?xml version="1.0" encoding="utf-8"?>
- <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">
- <StackLayout VerticalOptions="CenterAndExpand" HorizontalOptions="Center">
- <Entry x:Name="txtText" Placeholder="Write some text..."></Entry>
- <Button x:Name="btnWrite" Text="Write"></Button>
- <Button x:Name="btnRead" Text="Read"></Button>
- <Label x:Name="lblFileTexts" HorizontalTextAlignment="Center" LineBreakMode="WordWrap" Text="File Values:"></Label> </StackLayout>
- </ContentPage>
Call DependencyService
In this step, call DependencyService for your PCL.
- using Xamarin.Forms;
- namespace XamarinForms_Files {
- public partial class XamarinForms_FilesPage: ContentPage {
- string fileName = "MyFile.txt";
- public XamarinForms_FilesPage() {
- InitializeComponent();
- btnWrite.Clicked += (sender, e) => {
- string data = txtText.Text;
-
- DependencyService.Get < IFileReadWrite > ().WriteData(fileName, data);
- txtText.Text = string.Empty;
- };
- btnRead.Clicked += (sender, e) => {
-
- string data = DependencyService.Get < IFileReadWrite > ().ReadData(fileName);
- lblFileTexts.Text = data;
- };
- }
- }
- }
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.