Windows 7 Phone – Saving to Isolated Storage

I was recently asked how to save a serialised file to the Windows 7 phone isolated storage so I thought I’d post an example, similar to how I did this within my Windows 7 phone database Rapid Repository.

In this post, I’m going to show a simple example of:

  • Creating a directory
  • Building the file path
  • Saving the file

To see how to load a file from isolated storage, see the following post http://weblogs.asp.net/seanmcalinden/archive/2010/11/18/windows-7-phone-loading-from-isolated-storage.aspx.

This post assumes that you have a serialised json file to save that is passed into the Save method along with a file name.

Here we go…

Save to isolated storage
  1. public class SaveToIsolatedStorage
  2. {
  3.     private string myDirectory = "MyDirectory";
  4.  
  5.     public void Save(string fileName, string jsonFile)
  6.     {
  7.         try
  8.         {
  9.             using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
  10.             {
  11.                 fileName = String.Format("{0}.json", fileName);
  12.                 string filePath = Path.Combine(myDirectory, fileName);
  13.  
  14.                 if (!store.DirectoryExists(myDirectory))
  15.                 {
  16.                     store.CreateDirectory(myDirectory);
  17.                 }
  18.  
  19.                 using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filePath, FileMode.Create, store))
  20.                 {
  21.                     using (StreamWriter stream = new StreamWriter(fileStream))
  22.                     {
  23.                         stream.Write(jsonFile);
  24.                     }
  25.                 }
  26.             }
  27.         }
  28.         catch (IsolatedStorageException exception)
  29.         {
  30.             throw exception;
  31.         }
  32.     }
  33. }

As you can see,  we get the user store for the application, this is then used for all our interaction with the isolated storage file system.

Once we have the store, a directory called MyDirectory is created if it doesn’t already exist.

Once we’re happy the directory exists we open a file stream and then use a stream writer to write the json file to isolated storage.

 

I hope that this is useful, if you would like to see a more ‘real world’ example – you can view the source of the Rapid Repository FileManager class here.

Kind Regards,

Sean McAlinden.

1 Comment

Comments have been disabled for this content.