Search

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Saturday, December 17, 2016

Local File Storage using Xamarin Forms

Introduction:
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. We can share most of the xamarin form code to multiple platform .All the mobile platform have they are own file system like read,write,delete file . we don’t have any direct API for sharing File System using xamarin form .
Xamarin recommending third -party component called PCLStorage. We can Share our file storage library to all platform. No need to write separately

PCLStorage :
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.
Here is a sample showing how you can use PCL Storage to create a folder and write to a text file in that folder:
I have created Sample application and published the Basic Storage Recipes sample using xamarin Form .Download the sample to see working examples of the programming tasks.
Here’s the list of tasks demonstrated in the Basic Storage Recipes sample:
Local Storage IOSLocal Storage Windows

In addition to showing you how to work with files and PCL Storage sample also demonstrates the following tasks:
  • Read File
  • Write file
  • Create Folder
  • Check folder and file exists
  • Save Image
  • Read Image
  • Delete File
  • Replace file
Create New Xamarin.Form Application:
Xamarin.Forms is a cross platform UI toolkit, which allows the user to efficiently create native user interface layout. Code can be shared with all the devices (IOS, Android, Windows Phone and Win store app) .just refer my previous article for create new xamarin Form application from http://www.c-sharpcorner.com/article/how-to-create-first-xamarin-form-application/


Add PCLStorage Nuget Package:
Add PCLStorage Nuget package to all the project. Right click on Project Solution ➔ Click on “Manage Nuget package for Solution “➔ Search and Select “PCLStorage”➔ Select all the Project ➔Click on Install.


And start create code from portable library like below
Cross platform Local Folder:
In xamarin.Form, the PCLStorage API will help us to retrieve all platform local folder name and path using below code .no need to write any platform specific code for access local folder
Using PCLStorage;

IFolder folder = FileSystem.Current.LocalStorage;


Creating new folders
To create a new subfolder in the local folder, call the CreateFolderAsync method.
String folderName =”csharp” ;
IFolder folder = FileSystem.Current.LocalStorage;
           folder = await folder.CreateFolderAsync(folderName, CreationCollisionOption.ReplaceExisting);


Create New file:
To create a new file in the local folder, call the CreateFileAsync method.

String filename=”username.txt”;
IFolder folder = FileSystem.Current.LocalStorage;
           IFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);


Check Folder Already Exists:
we can check for an existing folder in a particular folder like below
  public async static Task<bool> IsFolderExistAsync(this string folderName, IFolder rootFolder = null)
       {
           // get hold of the file system
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           ExistenceCheckResult folderexist = await folder.CheckExistsAsync(folderName);
           // already run at least once, don't overwrite what's there
           if (folderexist == ExistenceCheckResult.FolderExists)
           {
               return true;

           }
           return false;
       }


Check File Already Exists:
we can check for an existing file in a particular folder like below
public async static Task<bool> IsFileExistAsync(this string fileName, IFolder rootFolder = null)
       {
           // get hold of the file system
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           ExistenceCheckResult folderexist = await folder.CheckExistsAsync(fileName);
           // already run at least once, don't overwrite what's there
           if (folderexist == ExistenceCheckResult.FileExists)
           {
               return true;

           }
           return false;
       }


Delete File:
we can use DeleteAsync methos for delete file
 public async static Task<bool> DeleteFile(this string  fileName, IFolder rootFolder = null)
       {
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           bool exist = await fileName.IsFileExistAsync(folder);
           if (exist == true)
           {
               IFile file = await folder.GetFileAsync(fileName);
               await file.DeleteAsync();
               return true;
           }
           return false;
       }


Write File:
If you want to write any extension file document just use WriteAllTextAsync method for write
  public async static Task<bool> WriteTextAllAsync(this string filename, string content = "", IFolder rootFolder = null)
       {
           IFile file = await filename.CreateFile(rootFolder);
           await file.WriteAllTextAsync(content);
           return true;
       }


Read File:
If you want to read any extension file document just use ReadAllTextAsync method for write
  public async static Task<string> ReadAllTextAsync(this string fileName, IFolder rootFolder = null)
       {
           string content = "";
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           bool exist = await fileName.IsFileExistAsync(folder);
           if (exist == true)
           {
               IFile file = await folder.GetFileAsync(fileName);
               content = await file.ReadAllTextAsync();
           }
           return content;
       }


Save Image:
We can save image using PCLStorage like below
public async static Task SaveImage(this byte[] image,String fileName, IFolder rootFolder = null)
       {
           // get hold of the file system
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;

           // create a file, overwriting any existing file
           IFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

           // populate the file with image data
           using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
           {
               stream.Write(image, 0, image.Length);
           }
       }


Get Image:
We can load image using PCLStorage like below
public async static Task<byte[]> LoadImage(this byte[] image, String fileName, IFolder rootFolder = null)
       {
           // get hold of the file system
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;

           //open file if exists
           IFile file = await folder.GetFileAsync(fileName);
           //load stream to buffer
           using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
           {
               long length = stream.Length;
               byte[] streamBuffer = new byte[length];
               stream.Read(streamBuffer, 0, (int)length);
               return streamBuffer;
           }
           
       }


PCL Helper Class:
I have created very simple PCLHelper class. you can refer and reuse in your project
using PCLStorage;
using System;
using System.Threading.Tasks;

namespace DevEnvExe_LocalStorage
{
   public static class PCLHelper
   {
   
       public async static Task<bool> IsFileExistAsync(this string fileName, IFolder rootFolder = null)
       {
           // get hold of the file system
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           ExistenceCheckResult folderexist = await folder.CheckExistsAsync(fileName);
           // already run at least once, don't overwrite what's there
           if (folderexist == ExistenceCheckResult.FileExists)
           {
               return true;

           }
           return false;
       }

       public async static Task<bool> IsFolderExistAsync(this string folderName, IFolder rootFolder = null)
       {
           // get hold of the file system
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           ExistenceCheckResult folderexist = await folder.CheckExistsAsync(folderName);
           // already run at least once, don't overwrite what's there
           if (folderexist == ExistenceCheckResult.FolderExists)
           {
               return true;

           }
           return false;
       }

       public async static Task<IFolder> CreateFolder(this string folderName, IFolder rootFolder = null)
       {
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           folder = await folder.CreateFolderAsync(folderName, CreationCollisionOption.ReplaceExisting);
           return folder;
       }

       public async static Task<IFile> CreateFile(this string filename, IFolder rootFolder = null)
       {
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           IFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
           return file;
       }
       public async static Task<bool> WriteTextAllAsync(this string filename, string content = "", IFolder rootFolder = null)
       {
           IFile file = await filename.CreateFile(rootFolder);
           await file.WriteAllTextAsync(content);
           return true;
       }

       public async static Task<string> ReadAllTextAsync(this string fileName, IFolder rootFolder = null)
       {
           string content = "";
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           bool exist = await fileName.IsFileExistAsync(folder);
           if (exist == true)
           {
               IFile file = await folder.GetFileAsync(fileName);
               content = await file.ReadAllTextAsync();
           }
           return content;
       }
       public async static Task<bool> DeleteFile(this string  fileName, IFolder rootFolder = null)
       {
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;
           bool exist = await fileName.IsFileExistAsync(folder);
           if (exist == true)
           {
               IFile file = await folder.GetFileAsync(fileName);
               await file.DeleteAsync();
               return true;
           }
           return false;
       }
       public async static Task SaveImage(this byte[] image,String fileName, IFolder rootFolder = null)
       {
           // get hold of the file system
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;

           // create a file, overwriting any existing file
           IFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

           // populate the file with image data
           using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
           {
               stream.Write(image, 0, image.Length);
           }
       }

       public async static Task<byte[]> LoadImage(this byte[] image, String fileName, IFolder rootFolder = null)
       {
           // get hold of the file system
           IFolder folder = rootFolder ?? FileSystem.Current.LocalStorage;

           //open file if exists
           IFile file = await folder.GetFileAsync(fileName);
           //load stream to buffer
           using (System.IO.Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
           {
               long length = stream.Length;
               byte[] streamBuffer = new byte[length];
               stream.Read(streamBuffer, 0, (int)length);
               return streamBuffer;
           }
           
       }
   }
}



I believe this will helpful for all the xamarin developer. If you have any question /others, please Post in Comment box



4 comments:

  1. Replies
    1. Devenvexe.Com/Xamarin: Local File Storage Using Xamarin Forms >>>>> Download Now

      >>>>> Download Full

      Devenvexe.Com/Xamarin: Local File Storage Using Xamarin Forms >>>>> Download LINK

      >>>>> Download Now

      Devenvexe.Com/Xamarin: Local File Storage Using Xamarin Forms >>>>> Download Full

      >>>>> Download LINK IG

      Delete
  2. Woah!! Such a piece of the nice information you have shared here, I have read the entire post and I must say that the information is very helpful for me.
    xamarin development company

    ReplyDelete
  3. Devenvexe.Com/Xamarin: Local File Storage Using Xamarin Forms >>>>> Download Now

    >>>>> Download Full

    Devenvexe.Com/Xamarin: Local File Storage Using Xamarin Forms >>>>> Download LINK

    >>>>> Download Now

    Devenvexe.Com/Xamarin: Local File Storage Using Xamarin Forms >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete