Read and Write XML – Isolated Storage

Usually there is certain user related  info we would like to store in other place rather than the database.  For this task, we have several options, storing a a regular file, using the registry to save the settings, and so on.

The .Net framework also gives us the choice to use Isolated Storage,  basically the .Net handles the location of the file and its different for os user and for application.  I won’t go into the details of the Isolated Storage mechanism, but if you would like to have more info visit this link

Msdn Isolated Storage

For this example we would write the info of a DataSet to a xml file using Isolated Storage.
Writting part:
//Get the isolated store for this assembly
isf = IsolatedStorageFile.GetUserStoreForAssembly();
//Create a file at the top level of the store
isfStream = new IsolatedStorageFileStream("DB_Dump.xml", FileMode.OpenOrCreate, FileAccess.Write, isf);

//Create our streamwritter to write content to the file
StreamWriter sw = new StreamWriter(isfStream);

//assign a table to datatable
DataTable dt = ds.Tables[0];

//Write the content of the datatable to my xml file
dt.WriteXml(sw,XmlWriteMode.WriteSchema);

//it is very important to include the XmlWriteMode.WriteSchema,

//otherwise we'll get errors reading the xml file

Now for the reading part:
//Get the isolated store for this assembly
isf = IsolatedStorageFile.GetUserStoreForAssembly();
//Open a file at the top level of the store
isfStream = new IsolatedStorageFileStream("DB_Dump.xml", FileMode.Open, FileAccess.Read, isf);

//Our streamreader to read data
StreamReader sr = new StreamReader(isfStream);

//assign a table to datatable
DataTable dt = new DataTable();

dt.ReadXml(sr.ReadToEnd());

As you can see, its pretty straightforward. The only special consideration is setting the XmlWriteMode to Write Schema.

~ by ajhorus on July 16, 2007.

Leave a Reply