5.4. Serializing Data

Problem

You need to serialize the contents of a DataSet so that you can store the data on a disk or transfer it across a network.

Solution

You can serialize a DataSet into XML, binary, or SOAP formats and save the serialized DataSet to a stream (such as a file or network stream).

The sample code creates a DataSet containing the Orders and Order Details tables from Northwind and a relation between the two tables. A file stream is created and the DataSet is serialized to the stream using a specified format.

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

Example 5-4. File: SerializeForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.IO; using System.Data; using System.Data.SqlClient; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Xml.Serialization; // Table name constants private const String ORDERS_TABLE = "Orders"; private const String ORDERDETAILS_TABLE = "OrderDetails"; // Relation name constants private const String ORDERS_ORDERDETAILS_RELATION = "Orders_OrderDetails_Relation"; // Field name constants private const String ORDERID_FIELD = "OrderID"; private SaveFileDialog sfd; // . . . private void goButton_Click(object sender, System.EventArgs e) { DataSet ds = new DataSet( ); SqlDataAdapter da; // Fill the Order table and add it to the DataSet. da = new SqlDataAdapter("SELECT * FROM Orders", ...

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.