windows phone 7 serialize object to isolated storage

November 16, 2011 at 11:41 PMdsoltesz

I have been working with windows phone 7 recently and i want to be able to serialize an object to xml to save into isolated storage.  Here is a Isolated storage helper that will allow you to do jus that.

public class IsolatedStorageHelper
    {
        public const string MyObjectFile = "myObject.xml";
        public static void WriteToXml<T>(T data, string path)
        {
            // Write to the Isolated Storage
            var xmlWriterSettings = new XmlWriterSettings { Indent = true };

            using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = myIsolatedStorage.OpenFile(path, FileMode.Create))
                {
                    var serializer = new XmlSerializer(typeof(T));
                    using (var xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
                    {
                        serializer.Serialize(xmlWriter, data);
                    }
                }
            }
        }
        public static T ReadFromXml<T>(string path)
        {
            T data = default(T);
            try
            {
                using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var stream = myIsolatedStorage.OpenFile(path, FileMode.Open))
                    {
                        var serializer = new XmlSerializer(typeof(T));
                        data = (T)serializer.Deserialize(stream);
                    }
                }
            }
            catch
            {    //add some code here
            }
            return data;
        }


    }

To save your object call

IsolatedStorageHelper.WriteToXml(MyObject, IsolatedStorageHelper.MyObjectFile);

To fetch your object

var myObject = IsolatedStorageHelper.ReadFromXml<MyObject> (IsolatedStorageHelper.MyObjectFile);

Posted in: .NET | c# | silverlight | Windows Phone 7

Tags: , , ,

Comments (1) -

It took me about 15 minutes to realize, there's an error in the code to fetch the objects, you're missing a ( before isolatedStorageHelper.

Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading