Using Generics and Isolated Storage

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.

Up ↑

%d bloggers like this: