Understanding Isolated Storage in Silverlight

In the previous article we learned the fundamentals of Isolated Storage and how to write to files in isolated storage using the same classes you use for ordinary file access in a .NET application, such as StreamWriter and BinaryWriter. To read from them, you use the corresponding StreamReader and BinaryReader classes. Although this approach gives us the most direct control over your files, it's not the only option.

So, here in the second of a two-part series of articles, we will learn about the XmlSerializer class, which provides a higher-level alternative that allows you to serialize and deserialize objects rather than write and read individual pieces of data.

How it works:

XmlSerializer works by converting a live object into a stream of bytes, which you can push out to any stream and perform the reverse trick and convert a stream of bytes into an object instance.

How to use it:we need to add, System.Xml.Serialization.dll

Advantage with XML Serializer:

XmlSerializer gives you a clean, concise way to store an entire object's worth of information. Ideally, the classes we use to store information with XmlSerializer will be simple data packages with little or no functionality built in.

// We will create a data file with employee name using(FileStream sw = store.CreateFile(emp.Name + ".employee")) {//Serializer method is used to serialize the object, which is emp here; serializer.Serialize(sw,emp); }//Let us add the information in our listbox to show lstPeople.ItemsSource = store.GetFileNames("*employee"); currentEmployee =null; txtFirstName.Text= ""; } }

Step 6: Now let us write handler for ListBox Selection Changed. The idea behind that is that when we hover over a listbox item, we will populate in textBox. When the user clicks one of the employee files in the list, the data is retrieved from isolated storage; we will perform deserialization, back to object from stream.

privatevoid lstPeople_SelectionChanged(object sender, SelectionChangedEventArgs e) {if (lstPeople.SelectedItem == null)return;//Define the store object scope,i.e. application or site.using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) {//Define the stream object to read , and keep the file mode Open.using(FileStream streamReader =store.OpenFile(lstPeople.SelectedItem.ToString(), FileMode.Open)) {//Cast the object into Class type.//While saving/ serilization , we used Serialize() , similarly now we will use Deserialize()// to get the object back into employee type.

}Step 8: Press F5 and type few employee names, click to save. Select any employee name from list box to view detail in textbox. This all is happening in scope of Isolated Storage as we are using to store the serialized data.

Conclusion :

So we learned how can we use XmlSerializerclass to write to files in isolated storage.