Xamarin.Forms - Working With Directory Using DependencyService

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files are the most easily done tasks using native file APIs on each platform. Alternatively, embedded resources are also 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 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
  1. Interface – The required functionality is defined by an interface in shared code.
  2. Implementation Per Platform – Classes that implement the interface must be added to each platform project.
  3. 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.
  4. Call to DependencyService – Shared code needs to explicitly call DependencyService to ask for implementations of the interface.
Following Topic Covered.
  • Create Directory
  • Rename Directory
  • Delete Directory
Related Post
Prerequisites
  • Visual Studio 2017(Windows or Mac)
The steps given below are required to be followed in order to create a Directory, rename it, and delete 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 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 - interface in Xamarin.Forms PCL.

Go to Solution—>PCL—>Right click—>New—>Empty Class—>IDirectory.cs.



Now, write the following code.

IDirectory.cs
  1. using System;  
  2. namespace XamarinForms_Files  
  3. {  
  4.     public interface IDirectory {  
  5.         string CreateDirectory(string directoryName);  
  6.         void RemoveDirectory();  
  7.         string RenameDirectory(string oldDirectoryName, string newDirectoryName);  
  8.     }  
  9. }  
 
Implementation per platform - iOS Implementation

Go to Solution—>iOS—>Right click—>New—>Empty Class—> DirectoryHelper.cs.

 
 
Now, write the following code.

DirectoryHelper.cs
  1. using System;  
  2. using System.IO;  
  3. using Xamarin.Forms;  
  4. using XamarinForms_Files.iOS;  
  5. [assembly: Dependency(typeof(DirectoryHelper))]  
  6. namespace XamarinForms_Files.iOS {  
  7.     public class DirectoryHelper: IDirectory {  
  8.         public string documentBasePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);  
  9.         public string CreateDirectory(string directoryName) {  
  10.             var directoryPath = Path.Combine(documentBasePath, directoryName);  
  11.             if (!Directory.Exists(directoryPath)) {  
  12.                 Directory.CreateDirectory(directoryPath);  
  13.             }  
  14.             return directoryPath;  
  15.         }  
  16.         public void RemoveDirectory() {  
  17.             DirectoryInfo directory = new DirectoryInfo(documentBasePath);  
  18.             foreach(DirectoryInfo dir in directory.GetDirectories()) {  
  19.                 dir.Delete(true);  
  20.             }  
  21.         }  
  22.         public string RenameDirectory(string oldDirectoryName, string newDirectoryName) {  
  23.             var olddirectoryPath = Path.Combine(documentBasePath, oldDirectoryName);  
  24.             var newdirectoryPath = Path.Combine(documentBasePath, newDirectoryName);  
  25.             if (Directory.Exists(olddirectoryPath)) {  
  26.                 Directory.Move(olddirectoryPath, newdirectoryPath);  
  27.             }  
  28.             return newdirectoryPath;  
  29.         }  
  30.     }  
  31. }  


Android Implementation

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

 

Now, write the following code.

DirectoryHelper.cs
  1. using System;  
  2. using System.IO;  
  3. using Xamarin.Forms;  
  4. using XamarinForms_Files.Droid;  
  5. [assembly: Dependency(typeof(DirectoryHelper))]  
  6. namespace XamarinForms_Files.Droid {  
  7.     public class DirectoryHelper: IDirectory {  
  8.         public string documentBasePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);  
  9.         public string CreateDirectory(string directoryName) {  
  10.             var directoryPath = Path.Combine(documentBasePath, directoryName);  
  11.             if (!Directory.Exists(directoryPath)) {  
  12.                 Directory.CreateDirectory(directoryPath);  
  13.             }  
  14.             return directoryPath;  
  15.         }  
  16.         public void RemoveDirectory() {  
  17.             DirectoryInfo directory = new DirectoryInfo(documentBasePath);  
  18.             foreach(DirectoryInfo dir in directory.GetDirectories()) {  
  19.                 dir.Delete(true);  
  20.             }  
  21.         }  
  22.         public string RenameDirectory(string oldDirectoryName, string newDirectoryName) {  
  23.             var olddirectoryPath = Path.Combine(documentBasePath, oldDirectoryName);  
  24.             var newdirectoryPath = Path.Combine(documentBasePath, newDirectoryName);  
  25.             if (!Directory.Exists(olddirectoryPath)) {  
  26.                 Directory.Move(olddirectoryPath, newdirectoryPath);  
  27.             }  
  28.             return newdirectoryPath;  
  29.         }  
  30.     }  
  31. }  
 

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="txtDirectory" Placeholder="Enter Directory Name..."></Entry>  
  5.         <Button x:Name="btnCreate" Text="Create"></Button>  
  6.         <Entry x:Name="txtDirectoryRename" Placeholder="Enter New Directory Name..."></Entry>  
  7.         <Button x:Name="btnRename" Text="Rename"></Button>  
  8.         <Button x:Name="btnRemove" Text="Remove"></Button> </StackLayout>  
  9. </ContentPage>  
 
Call to DependencyService

In this step, call the DependencyService for your PCL.
  1. using Xamarin.Forms;  
  2. namespace XamarinForms_Files {  
  3.     public partial class XamarinForms_FilesPage: ContentPage {  
  4.         string oldDirectoryName;  
  5.         public XamarinForms_FilesPage() {  
  6.             InitializeComponent();  
  7.             btnCreate.Clicked += (sender, e) => {  
  8.                 oldDirectoryName = txtDirectory.Text;  
  9.                 //Create a Directory Using DependencyService  
  10.                 DependencyService.Get < IDirectory > ().CreateDirectory(txtDirectory.Text);  
  11.             };  
  12.             btnRename.Clicked += (sender, e) => {  
  13.                 //Rename Directory Using DependencyService  
  14.                 DependencyService.Get < IDirectory > ().RenameDirectory(oldDirectoryName, txtDirectoryRename.Text);  
  15.             };  
  16.             btnRemove.Clicked += (sender, e) => {  
  17.                 //Remove Directory Using DependencyService  
  18.                 DependencyService.Get < IDirectory > ().RemoveDirectory();  
  19.             };  
  20.         }  
  21.     }  
  22. }  
 

Click the Play button to try it out.
 
 

Here is the output. 


 
 
 
 


I hope you have understood how to create a Directory, rename it, and delete a file using DependencyService.
 
Thanks for reading. Please share comments and feedback.

Up Next
    Ebook Download
    View all
    Learn
    View all