How To Operate With Data Persistence In Xamarin.Forms - Part Two

Previous part

Introduction

Welcome back to the "Data Persistence in Xamarin.Forms" series. In the previous chapter, we saw how to save the user’s preferences. In this one, I’ll show you how to use file system to save data using Xamarin with the .Forms UI Technology and the PCL (Portable Class Library) code sharing strategy.

Before coding, just a little refresher about the Xamarin.Forms code sharing logic.

When we code in Xamarin.Forms environment, we’ve got to keep in mind that not all code can be sharable. Indeed, the following are not sharable and they need to be implemented with a platform-specific approach:

  • Uses files and folders on the device (We are concerned about in this tutorial)
  • Access system information
  • Access personal information
  • Uses external devices.

Also, we can use three methods to implement the write/read text using the file system:

  • Text
  • Json
  • Xml

To simplify the argument, in this tutorial, I’ll use only the text method.

Moreover, I’ll not show you how to manipulate saved data because that is out of the scope of the present tutorial. I’ll cover the manipulation data methods in a future article.

It’s important to say, before starting, that I’ll use “basic code method” and not the “clean code” one, because the purpose of the present tutorial is to show you the basics to save data.

Prerequisites

  • IDE: Visual Studio 2017 Community Edition.

The steps given below will lead you to the goal.

Part 2

File System

Step 1

Launch Visual Studio and create a default application.

Xamarin

Xamarin

Xamarin

Step 2

Now, we need to customize the User Inteface, adding an Entry, a Button and a ListView. Please note that the ListView has been added to show you that the code works. To do that, go to Solution Explorer, expand the solution Portable node, open the MainPage.xaml file, and replace the auto-generated code with the given one. 
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:StoreWithFileSys"  
  5.              x:Class="StoreWithFileSys.MainPage">  
  6.   
  7.   
  8.     <ContentPage.Padding>  
  9.         <OnPlatform x:TypeArguments="Thickness" iOS="0,20,0,0" />  
  10.     </ContentPage.Padding>  
  11.   
  12.     <StackLayout>  
  13.         <Entry x:Name="wroteText"   
  14. Placeholder="Insert your text here"HorizontalTextAlignment="Center" />  
  15.        <Button x:Name="saveBtn" Text="Save" Clicked="saveBtn_Clicked" />  
  16.   
  17.         <ListView x:Name="textsList">  
  18.             <ListView.ItemTemplate>  
  19.                 <DataTemplate>  
  20.                     <TextCell Text="{Binding}" />  
  21.                 </DataTemplate>  
  22.             </ListView.ItemTemplate>  
  23.         </ListView>  
  24.     </StackLayout>  
  25. </ContentPage>   

Step 3

Now, we are going to connect the User Interface to the engine, in the Code Behind of the app. Our goal is to save the data written into the Entry field and show those in the ListView.

To do that, go to Solution Explorer, expand the solution Portable node, open the MainPage.xaml.cs file , delete the auto-generated code and write the following. 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7. using StoreWithFileSys;  
  8.   
  9.   
  10. namespace StoreWithFileSys  
  11. {  
  12.     public partial class MainPage : ContentPage  
  13.     {  
  14.         FileEngine fileEngine = new FileEngine();  
  15.   
  16.         public MainPage()  
  17.         {  
  18.             InitializeComponent();  
  19.             Refresh();  
  20.         }  
  21.   
  22.         async void saveBtn_Clicked(object sender, EventArgs e)  
  23.         {  
  24.             string storedText = wroteText.Text;  
  25.             await fileEngine.WriteTextAsync(wroteText.Text, "");  
  26.             wroteText.Text = "";  
  27.             Refresh();           
  28.         }  
  29.   
  30.         async void TextsList_Selected(object sender, SelectedItemChangedEventArgs e)  
  31.         {  
  32.             string storedText = (string)e.SelectedItem;  
  33.             wroteText.Text = storedText;  
  34.         }  
  35.   
  36.         async void Refresh()  
  37.         {  
  38.             textsList.ItemsSource = await fileEngine.GetFilesAsync();  
  39.             textsList.SelectedItem = null;  
  40.         }  
  41.     }  
  42. }   

Step 4

Now we need to implement the engine to store our data. When we use the Xamarin.Forms Environment, to save data with File System we’ve got to use Dependency Service to have access to Input/Output functions, add an Interface in the PCL Project to define functions, implement the interface with a platform-specific approach for each OS and connect the entire code using a Class added in a PCL project. Let me show you the code:

Create an interface in PCL Project

(right click on the Portable Project -> Add -> New Item -> Code -> Interface) and write the following code, 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace StoreWithFileSys  
  8. {  
  9.     public interface IFileEngine  
  10.     {  
  11.         Task WriteTextAsync(string storedText, string text);  
  12.         Task<string> ReadTextAsync(string storedText);  
  13.         Task<IEnumerable<string>> GetFilesAsync();  
  14.     }  
  15. }  

Xamarin

Implement the Interface for Android Engine

(right click on the Android Project -> Add -> New Item -> Visual C# ->Class) and write the following code, 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.IO;  
  6. using Xamarin.Forms;  
  7. using StoreWithFileSys;  
  8. using System.Threading.Tasks;  
  9.   
  10. [assembly: Dependency(typeof(StoreWithFileSys.Droid.FileEngine))]  
  11.   
  12.   
  13. namespace StoreWithFileSys.Droid  
  14. {  
  15.     class FileEngine : IFileEngine  
  16.     {  
  17.         public Task<IEnumerable<string>> GetFilesAsync()  
  18.         {  
  19.             IEnumerable<string> storedTexts =  
  20.                 from filePath in Directory.EnumerateFiles(DocsPath())  
  21.                 select Path.GetFileName(filePath);  
  22.                 return Task<IEnumerable<string>>.FromResult(storedTexts);  
  23.         }  
  24.   
  25.         public async Task<string> ReadTextAsync(string storedText)  
  26.         {  
  27.             string filePath = FilePath(storedText);  
  28.             using (StreamReader reader = File.OpenText(filePath))  
  29.             {  
  30.                 return await reader.ReadToEndAsync();  
  31.             }  
  32.         }  
  33.   
  34.         public async Task WriteTextAsync(string storedText, string text)  
  35.         {  
  36.             string filePath = FilePath(storedText);  
  37.             using (StreamWriter writer = File.CreateText(filePath))  
  38.             {  
  39.                 await writer.WriteAsync(text);  
  40.             }  
  41.         }  
  42.   
  43.         private string FilePath(string storedText)  
  44.         {  
  45.             return Path.Combine(DocsPath(), storedText);  
  46.         }  
  47.   
  48.         private string DocsPath()  
  49.         {  
  50.             return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);  
  51.         }  
  52.     }  
  53. }  

Xamarin

Implement the Interface for iOS Engine

(right click on the Android Project -> Add -> New Item -> Code ->Class) and write the following code, 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.IO;  
  6. using Xamarin.Forms;  
  7. using StoreWithFileSys;  
  8. using System.Threading.Tasks;  
  9.   
  10. [assembly: Dependency(typeof(StoreWithFileSys.iOS.FileEngine))]  
  11.   
  12.   
  13. namespace StoreWithFileSys.iOS  
  14. {  
  15.     class FileEngine : IFileEngine  
  16.     {  
  17.         public Task<IEnumerable<string>> GetFilesAsync()  
  18.         {  
  19.             IEnumerable<string> storedTexts =  
  20.                 from filePath in Directory.EnumerateFiles(DocsPath())  
  21.                 select Path.GetFileName(filePath);  
  22.                 return Task<IEnumerable<string>>.FromResult(storedTexts);  
  23.         }  
  24.   
  25.         public async Task<string> ReadTextAsync(string storedText)  
  26.         {  
  27.             string filePath = FilePath(storedText);  
  28.             using (StreamReader reader = File.OpenText(filePath))  
  29.             {  
  30.                 return await reader.ReadToEndAsync();  
  31.             }  
  32.         }  
  33.   
  34.         public async Task WriteTextAsync(string storedText, string text)  
  35.         {  
  36.             string filePath = FilePath(storedText);  
  37.             using (StreamWriter writer = File.CreateText(filePath))  
  38.             {  
  39.                 await writer.WriteAsync(text);  
  40.             }  
  41.         }  
  42.   
  43.         private string FilePath(string storedText)  
  44.         {  
  45.             return Path.Combine(DocsPath(), storedText);  
  46.         }  
  47.   
  48.         private string DocsPath()  
  49.         {  
  50.             return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);  
  51.         }  
  52.     }  
  53. }  

Xamarin

Implement the Interface for UWP Engine
 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Threading.Tasks;  
  4. using Xamarin.Forms;  
  5. using Windows.Storage;  
  6. using System.Linq;  
  7.   
  8. [assembly: Dependency(typeof(StoreWithFileSys.UWP.FileEngine))]  
  9.   
  10. namespace StoreWithFileSys.UWP  
  11. {  
  12.     class FileEngine : IFileEngine  
  13.     {  
  14.   
  15.         public async Task WriteTextAsync(string storedText, string text)  
  16.         {  
  17.             StorageFolder userLocalFolder = ApplicationData.Current.LocalFolder;  
  18.             IStorageFile userStorageFile = await userLocalFolder.CreateFileAsync(storedText, CreationCollisionOption.ReplaceExisting);  
  19.             await FileIO.WriteTextAsync(userStorageFile, text);  
  20.         }  
  21.   
  22.         public async Task<string> ReadTextAsync(string storedText)  
  23.         {  
  24.             StorageFolder userLocalFolder = ApplicationData.Current.LocalFolder;  
  25.             IStorageFile userStorageFile = await userLocalFolder.GetFileAsync(storedText);  
  26.             return await FileIO.ReadTextAsync(userStorageFile);  
  27.         }  
  28.   
  29.         public async Task<IEnumerable<string>> GetFilesAsync()  
  30.         {  
  31.             StorageFolder userLocalFolder = ApplicationData.Current.LocalFolder;  
  32.             IEnumerable<string> storedTexts =  
  33.                 from userStorageFile in await userLocalFolder.GetFilesAsync()  
  34.                 select userStorageFile.Name;  
  35.             return storedTexts;  
  36.         }  
  37.     }  
  38. }  

Xamarin

Create a class to connect the entire code

(right click on the PCL Project -> Add -> New Item -> Code ->Class) and write the following code, 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.IO;  
  7. using Xamarin.Forms;  
  8.   
  9. namespace StoreWithFileSys  
  10. {  
  11.     class FileEngine : IFileEngine  
  12.     {  
  13.         IFileEngine fileEngine = DependencyService.Get<IFileEngine>();  
  14.   
  15.   
  16.         public Task<IEnumerable<string>> GetFilesAsync()  
  17.         {  
  18.             return fileEngine.GetFilesAsync();  
  19.         }  
  20.   
  21.         public Task<string> ReadTextAsync(string storedText)  
  22.         {  
  23.             return fileEngine.ReadTextAsync(storedText);  
  24.         }  
  25.   
  26.         public Task WriteTextAsync(string storedText, string text)  
  27.         {  
  28.             return fileEngine.WriteTextAsync(storedText, text);  
  29.         }  
  30.     }  
  31. }  

Xamarin

Step 5

Now, we’ll see the output on the three mobile platforms, on Windows desktop, and the relative behavior within:

Windows 10 Desktop

Xamarin

Windows 10 mobile

Xamarin

iOS

Xamarin

Android

Xamarin

Conclusions

In this tutorial I have shown you how to save data using the OS File System.

As you saw, the code above contains the “async method”. That’s important to avoid the block of the user interface during the data saving process. Indeed, the UWP data saving method must be asyncronus. Moreover, it’s a bit complicated to keep in mind that the data saving code is not sharable and needs the platform-specific implementation.

The “roadmap” of a build like that is the following

  • Build User Interface: -> Step n.2: to interact with the user.
  • Build Code Behind -> Step n. 3: to connect the UI to the engine of the app.
  • Build Interface -> Step n. 4: to say to the program what to do, but not how.
  • Implement interface for each concerned OS platform -> Step n. 4: because, as I said before, saving data process must be implemented with the platform-specific approach.
  • Build the class to unify the entire code -> Step n. 4: to allow the parts of the program to work together.

Of course, you can improve it, but that is out of our scope at this time.

Just another thing: the code shown above has an instructive purpose, but, if you are seaching for a easier way, you can use the PCLStorage plugin by Daniel Plaisted ( https://www.nuget.org/packages/PCLStorage/1.0.2/ ). You can find it in NuGet: PCL Storage provides a consistent, portable set of local file IO APIs for .NET, Windows Phone, Windows Store, Xamarin.iOS, Xamarin.Android, and Silverlight. This makes it easier to create cross-platform .NET libraries and apps.

I’ll cover this solution in a future tutorial, while, in the next one, I’ll show you how to save data in a database.

Thank you for your attention and interest