Copy file from XAP package to IsolatedStorage [Windows Phone 8]

In my last project i needed to copy a file (SQLite database) from my XAP package to the isolated storage directory of my phone. This task is not very straightforward so after a couple of researches on the internet I’ve found this code and so I decided to share it.

First we include a couple of namespaces.


using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Resources;
using System.Windows;

Then I’ve created a synchronous void sub to check if the file exist or not. If it doesn’t exist then we copy it from the xap package to the IS folder,


if(!IsolatedStorageFile.GetUserStoreForApplication().FileExists("database.db"))
 {
       StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("database.db", UriKind.Relative));
       using (IsolatedStorageFile isFile = IsolatedStorageFile.GetUserStoreForApplication())
       {
           using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("database.db", FileMode.Create, isFile))
           {
                using (BinaryWriter writer = new BinaryWriter(fileStream))
                {
                     Stream resourceStream = streamInfo.Stream;
                     long length = resourceStream.Length;
                     byte[] buffer = new byte[32];
                     int readCount = 0;
                     using (BinaryReader reader = new BinaryReader(streamInfo.Stream))
                     {
                         // read file in chunks in order to reduce memory consumption and increase performance
                         while (readCount < length)
                         {
                             int actual = reader.Read(buffer, 0, buffer.Length);
                             readCount += actual;
                             writer.Write(buffer, 0, actual);
                         }
                     }
                }
            }
       }
 }