O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.5. Deserializing Data

Problem

You have a DataSet that has been serialized and written to a file. You want to recreate the DataSet from this file.

Solution

Use the serializer object’s Deserialize( ) method and cast the result as a DataSet.

The sample code loads a file stream containing a previously serialized DataSet in a specified format and deserializes it to recreate the original DataSet.

The C# code is shown in Example 5-5.

Example 5-5. File: DeserializeForm.cs

// Namespaces, variables, and constants using System; using System.Windows.Forms; using System.IO; using System.Data; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Xml.Serialization; private OpenFileDialog ofd; // . . . private void goButton_Click(object sender, System.EventArgs e) { // Create and open the stream for deserializing. Stream stream = null; try { stream = File.Open(fileNameTextBox.Text, FileMode.Open, FileAccess.Read); } catch(Exception ex) { MessageBox.Show(ex.Message, "Deserializing Data", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Deserialize the DataSet from the stream. DataSet ds = null; try { if (xmlReadRadioButton.Checked) { ds = new DataSet( ); ds.ReadXml(stream); } else if (xmlSerializerRadioButton.Checked) { XmlSerializer xs = new XmlSerializer(typeof(DataSet)); ds = (DataSet)xs.Deserialize(stream); } else if(soapRadioButton.Checked) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required