To read and write generic objects to isolated storage, you will need to pass the object types. This is so the DataContractSerializer knows how to process the object.
So, to write data:
///
/// Write a generic object to Isolated Storage
///
/// Type of object being written
/// The object being written
/// The location to write the object to
private void WriteToIsolatedStorage(T dataToSave,string StreamLocation)
{
using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(StreamLocation, System.IO.FileMode.Create, isolatedStorageFile))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
dcs.WriteObject(fileStream, dataToSave);
}
}
}
and to read data:
///
/// Read a generic object from isolated storage
///
/// Type of the object being deserialised
/// Location of the isolated storage file.
/// A deserialised object of type T
private T ReadFromIsolatedStorage(String StreamLocation)
{
using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(StreamLocation, System.IO.FileMode.Open, isolatedStorageFile))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(T));
return (T)dcs.ReadObject(fileStream);
}
}
}
To consume these methods:
WriteToIsolatedStorage<List>(objListOfPersons, "PersonStore.xml");
WriteToIsolatedStorage(objOrders, "Orders.xml");
_objListOfPersons = ReadFromIsolatedStorage<List>("PersonStore.xml") as List;
_objOrders= ReadFromIsolatedStorage("Order.xml") as List;
Leave a Reply