windows phone 7 serialize object to isolated storage
November 16, 2011 at 11:41 PM
—
dsoltesz
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);