Serializing the DataSet Object as Binary Data

Serializing the DataSet Object as Binary Data

You can easily serialize a DataSet object to a binary file. The following code sample shows how to write the contents of a DataSet to a binary file.



using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace DataSetToBinary
{
class Program
{
static void Main(string[] args)
{

string strConnectString = "Data Source=(local);Integrated security=SSPI;Initial Catalog=AdventureWorks;";
string strText = "SELECT Top 2 * FROM Sales.Customer Order By ModifiedDate Desc";
// Create and fill a DataSet using a data adapter
SqlDataAdapter objDataAdapter = new SqlDataAdapter(strText, strConnectString);
DataSet objDataSet = new DataSet("CustomerData");
// Fill DataSet with customer record
objDataAdapter.Fill(objDataSet, "Customer");
// Write binary file for the DataSet
objDataSet.RemotingFormat = SerializationFormat.Binary;
FileStream fs = new FileStream(@"..\..\Customer.bin", FileMode.Create);
BinaryFormatter fmt = new BinaryFormatter();
fmt.Serialize(fs, objDataSet);
fs.Close( );
}
}
}


In this example we are first creating a BinaryFormatter object and then using it to create the binary file. Opening the binary file by using the Visual Studio hex editor would reveal that the binary file contains embedded XML.

 

We can also save the file as true binary data by adding the following line to the beginning after DataSet is populated.


 objDataSet.RemotingFormat = SerializationFormat.Binary;


Ebook Download
View all
Learn
View all