Serialization and Isolated Storage in WP7

Reading XML in and out from the provided Isolated Storage is important and quite simple, as the following code snippets illustrate. I have the methods constrained to a generic so that I can use this across all the WP7 applications that I am writing.

To write, the Isolated Storage allocated is called on by IsolatedStorageFile.GetUserStoreForApplication() where objects, XMLized by XmlSerializer serializer are written by the XmlWriter writer. The code is pretty telling, I think, so I’ll spare you the explanation.

public static void Write<T>(T obj, string fileName)
{
    XmlWriterSettings writerSettings =
            new XmlWriterSettings
            {
                Indent = true,
                IndentChars = "\t"
            };

    try
    {
        var store = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Create);

        XmlSerializer serializer = new XmlSerializer(typeof(T));

        using (XmlWriter xmlWriter = XmlWriter.Create(stream, writerSettings))
        {
            serializer.Serialize(xmlWriter, obj);
        }

        stream.Close();
    }
    catch (Exception emAll)
    {
        throw emAll;
    }
}

To read XMLized objects from storage, the following function is sufficient and pretty self explanatory. Again, the function is constrained to generic objects so that you can go crazy on what types you want to use it with.

public static T Read<T>(string fileName)
 {
     try
     {
         var store = IsolatedStorageFile.GetUserStoreForApplication();
         IsolatedStorageFileStream stream = store.OpenFile(fileName, FileMode.Open);

         XmlSerializer serializer = new XmlSerializer(typeof(T));
         return (T)serializer.Deserialize(stream);
    }
    catch (Exception emAll)
    {
        throw emAll;
    }
} 

Of course, you will have to modify Exception handling to suit your needs, these are only generalized samples. Also, the code can be improved, so write back with improvements that you might have come up with.


Follow

Get every new post delivered to your Inbox.

Join 256 other followers