Binary serialization of a DataSet is probably not the best plan. If you want to serialize an object that could be a different type, save to a database, and then later deserialize: what's the best option? I came up with something like this, but I'm open to suggestions. Thoughts? For example, what if my results could be a DataSet or could be an Exception - perhaps on an operation running on a worker thread? It would be nice to a function that could handle many types of objects to store.
using
System;
using
System.Data;
using
System.Xml.Serialization;
using
System.IO;
using
System.Runtime.Serialization.Formatters.Binary;
class
App
{
static byte[]
SerializeResults(object results)
{
MemoryStream mstream = new MemoryStream();
BinaryFormatter formatter = new
BinaryFormatter();
formatter.Serialize(mstream, results);
return mstream.GetBuffer();
}
static object
DeserializeResults(byte[] results)
{
MemoryStream mstream = new MemoryStream();
BinaryFormatter formatter = new
BinaryFormatter();
mstream.Write(results, 0, results.Length);
mstream.Position = 0;
object o = formatter.Deserialize(mstream);
return o;
}
[STAThread]
static void
Main(string[] args)
{
object theObject = null;
if(Environment.TickCount % 2 == 0)
{
DataSet ds = new DataSet("TestDataSet");
ds.Tables.Add("TestTable");
ds.Tables["TestTable"].Columns.Add("Time");
ds.Tables["TestTable"].Rows.Add(new
object[] {DateTime.Now.ToLongTimeString()});
theObject = ds;
}
else
{
Exception ex = new Exception("test exception");
theObject = ex;
}
byte[]
b = SerializeResults(theObject);
theObject = null;
object o = DeserializeResults(b);
if(o is DataSet)
{
DataSet someData = o as DataSet;
XmlSerializer ser = new XmlSerializer(typeof(DataSet));
ser.Serialize(Console.Out, someData);
}
else if(o
is Exception)
{
Exception someException = o as Exception;
Console.WriteLine(someException.Message);
}
}
}