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) ...
Get ADO.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.