Manipulating Isolated Storage on Windows Phone 7

Long time ago when I started my Windows Phone 7 project (long time due but now being ported to the 7.1 track and released for Mango), I was using Isolated Storage quite extensively.

I have managed to accumulate some code for reading and writing files as well as deleting files and creating directories. I thought I should share it and hopefully it will save some one a little time.

The specific functions available help doing the following:

  • Loading an XML file as an XDocument
  • Serializing an object to an XML file
  • Appending text to a text file
  • Deserializing an XML file to an object
  • Saving a binary stream to a file

You will have to add System.Xml.Linq and System.Xml.Serialization to your references in your project to get some of these functions to work, if you haven’t already done so.

The Log.WriteLine() rows can be substituted with Debug.WriteLine, or removed. The Log class is just a small logger I wrote to help me log to file, as I got errors when field testing my GPS functionality and hence couldn’t debug that in the emulator.

using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace AppUtils
{
   /// <summary>
   /// IsoStorageHandler class is responsible for all access to isolated storage
   /// </summary>
   public class IsoStorageHandler
   {
      private const string SENDER = "IsoStorageHandler";

      /// <summary>
      /// Retrieves an XML file from isolated storage
      /// </summary>
      /// <param name="path">Path to the file</param>
      /// <param name="fileName">Name of the file</param>
      /// <returns>XDocument result</returns>
      public static XDocument GetXmlFile(string path, string fileName)
      {
         if (FileExists(path, fileName))
         {
            return LoadXDocument(path, fileName);
         }
         else
         {
            return null;
         }
      }

      /// <summary>
      /// Saves an object to an XML file
      /// </summary>
      /// <typeparam name="T">Object type</typeparam>
      /// <param name="objectToSave">Object to serialize</param>
      /// <param name="path">Path to the XML file</param>
      /// <param name="fileName">Name of the XML file</param>
      /// <returns>A bool indicating success</returns>
      public static void SaveObjectToXmlFile<T>(T objectToSave, string path, string fileName)
      {
         ValidatePathExiststense(path);
         SerializeObjectToFile(objectToSave, path, fileName);
      }

      /// <summary>
      /// Appends text to a textfile
      /// </summary>
      /// <param name="message">the message</param>
      /// <param name="path">path to the file</param>
      /// <param name="file">name of the file</param>
      public static void AppendTextToFile(string message, string path, string file)
      {
         ValidatePathExiststense(path);
         WriteTextToStreamWriter(message, path, file);
      }

      /// <summary>
      /// Deserializes an XML file in isolated storage to an object structure
      /// </summary>
      /// <typeparam name="T">Object type</typeparam>
      /// <param name="path">Path to the file</param>
      /// <param name="fileName">Name of the file</param>
      /// <returns>The object structure</returns>
      public static T XmlToObject<T>(string path, string fileName)
      {
         Log.WriteLine(SENDER, "XmlToObject called");
         try
         {
            using (IsolatedStorageFile isolatedFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
               if (!DirectoryExists(path))
               {
                  Log.WriteLine(SENDER, path + " directory doesn't exist");
                  return default(T);
               }

               if (!FileExists(path, fileName))
               {
                  Log.WriteLine(SENDER, fileName + " file doesn't exist");
                  return default(T);
               }

               T result;
               using (IsolatedStorageFileStream stream = isolatedFile.OpenFile(path + "\" + fileName, FileMode.Open))
               {
                  XmlSerializer serializer = new XmlSerializer(typeof(T));
                  result = (T)serializer.Deserialize(stream);
                  stream.Close();
               }
               return result;
            }
         }
         catch (IsolatedStorageException ise)
         {
            Log.WriteLine(SENDER, "Isolated storage exception: " + ise.InnerException.ToString());
            throw ise;
         }
         catch (Exception ex)
         {
            Log.WriteLine(SENDER, "Exception: " + ex.InnerException.ToString());
            throw ex;
         }
      }

      /// <summary>
      /// Deletes a file
      /// </summary>
      /// <param name="path">Path to the file</param>
      /// <param name="fileName">The name of the file</param>
      /// <returns>A bool indicating success</returns>
      public void DeleteFile(string path, string fileName)
      {
         if (FileExists(path, fileName))
         {
            DeleteFileFromIsolatedStorage(path, fileName);
         }
      }

      /// <summary>
      /// Save a binary stream to isolated storage
      /// </summary>
      /// <param name="stream">the binary stream</param>
      /// <param name="path">the path to the file</param>
      /// <param name="fileName">the name of the file</param>
      /// <returns></returns>
      public static void SaveStreamToFile(Stream stream, string path, string fileName)
      {
         ValidatePathExiststense(path);
         WriteStreamToFile(stream, path, fileName);
      }

     private static void ValidatePathExiststense(string path)
      {
         if (!DirectoryExists(path))
         {
            CreateDirectory(path);
         }
      }

      private static void CreateDirectory(string path)
      {
         try
         {
            using (IsolatedStorageFile isoStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
               isoStorageFile.CreateDirectory(path);
            }
         }
         catch (IsolatedStorageException ise)
         {
            Log.WriteLine(SENDER, "Isolated storage exception: " + ise.InnerException.ToString());
            throw ise;
         }
      }

      private static XDocument LoadXDocument(string path, string fileName)
      {
         XDocument loadedXDocument = null;
         try
         {
            using (IsolatedStorageFile isolatedFile = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream stream = isolatedFile.OpenFile(path + "\" + fileName, FileMode.Open))
            {
               loadedXDocument = XDocument.Load(stream);
            }
         }
         catch (IsolatedStorageException ise)
         {
            Log.WriteLine(SENDER, "Isolated storage exception: " + ise.InnerException.ToString());
            throw ise;
         }
         return loadedXDocument;
      }

      private static void SerializeObjectToFile<T>(T objectToSave, string path, string fileName)
      {
         try
         {
            FileMode fileMode;
            if (FileExists(path, fileName))
            {
               fileMode = FileMode.Truncate;
            }
            else
            {
               fileMode = FileMode.OpenOrCreate;
            }

            using (IsolatedStorageFile isolatedFile = IsolatedStorageFile.GetUserStoreForApplication())
            using (IsolatedStorageFileStream stream = isolatedFile.OpenFile(path + "\" + fileName, fileMode))
            {
               XmlSerializer serializer = new XmlSerializer(typeof(T));
               serializer.Serialize(stream, objectToSave);
            }
         }
         catch (IsolatedStorageException ise)
         {
            Log.WriteLine(SENDER, "Isolated storage exception: " + ise.InnerException.ToString());
            throw ise;
         }
      }

      private static void WriteTextToStreamWriter(string message, string path, string file)
      {
         using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
         using (StreamWriter streamWriter = new StreamWriter(new IsolatedStorageFileStream(path + "//" + file, FileMode.Append, isolatedStorage)))
         {
            streamWriter.WriteLine(message);
            streamWriter.Close();
         }
      }

      private static bool FileExists(string path, string fileName)
      {
         try
         {
            using (IsolatedStorageFile isolatedFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
               if (isolatedFile.FileExists(path + "\" + fileName))
               {
                  Log.WriteLine(SENDER, "File: " + fileName + " exists.");
                  return true;
               }
               else
               {
                  Log.WriteLine(SENDER, "File: " + fileName + " doesn't exist.");
                  return false;
               }
            }
         }
         catch (IsolatedStorageException ise)
         {
            Log.WriteLine(SENDER, "Isolated storage exception: " + ise.InnerException.ToString());
            throw ise;
         }
      }

      private static bool DirectoryExists(string path)
      {
         try
         {
            using (IsolatedStorageFile isolatedFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
               return isolatedFile.DirectoryExists(path);
            }
         }
         catch (IsolatedStorageException ise)
         {
            Log.WriteLine(SENDER, "Isolated storage exception: " + ise.InnerException.ToString());
            throw ise;
         }
      }

      private bool DeleteFileFromIsolatedStorage(string path, string fileName)
      {
         try
         {
            using (IsolatedStorageFile isolatedFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
               isolatedFile.DeleteFile(path + "\" + fileName);
               Log.WriteLine(SENDER, fileName + " deleted");
               return true;
            }
         }
         catch (IsolatedStorageException ise)
         {
            Log.WriteLine(SENDER, "Isolated storage exception: " + ise.InnerException.ToString());
            throw ise;
         }
      }

      private static void WriteStreamToFile(Stream incommingStream, string path, string fileName)
      {
         try
         {
            using (IsolatedStorageFile isolatedStore = IsolatedStorageFile.GetUserStoreForApplication())
            using (var stream = new IsolatedStorageFileStream(path + "\" + fileName, FileMode.Create, FileAccess.Write, isolatedStore))
            using (BinaryWriter writer = new BinaryWriter(stream))
            {
               Stream resourceStream = incommingStream;
               long length = resourceStream.Length;
               byte[] buffer = new byte[32];
               int readCount = 0;
               using (BinaryReader reader = new BinaryReader(incommingStream))
               {
                  reader.BaseStream.Position = 0;
                  while (readCount < length)
                  {
                     int actual = reader.Read(buffer, 0, buffer.Length);
                     readCount += actual;
                     writer.Write(buffer, 0, actual);
                  }
               }

               Log.WriteLine(SENDER, "-- Created " + fileName + " file");
            }
         }
         catch (IsolatedStorageException ise)
         {
            Log.WriteLine(SENDER, "Isolated storage exception: " + ise.InnerException.ToString());
            throw ise;
         }
      }

   }
}

Happy coding 🙂

Manipulating Isolated Storage on Windows Phone 7
Tagged on:

One thought on “Manipulating Isolated Storage on Windows Phone 7

  • October 15, 2011 at 07:06
    Permalink

    Very well written article. It will be beneficial to everyone who utilizes it, as well as me. Keep doing what you are doing – looking forward to more posts.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.