Recently I was in the need to serialize a DataTable
as a string for further processing (storing in a file).
So I asked myself: How to serialize a DataTable into a string?
You can serialize a populated DataSet object to an XML file by executing the DataSet object's WriteXml method. You can serialize a populated DataSet object to an XML file by executing the DataSet object's WriteXml method.
DataTable is marked Serializable. Sure, but as I mentioned, if you take the Serializable tag off of the the Base class above, the BinaryFormatter will yell at you because the base class isn't serializable. DataTable's base isn't serializable.
Here is the code I wrote to perform the task of serializing a DataTable
into a string:
public static string SerializeTableToString( DataTable table )
{
if (table == null)
{
return null;
}
else
{
using (var sw = new StringWriter())
using (var tw = new XmlTextWriter(sw))
{
// Must set name for serialization to succeed.
table.TableName = @"MyTable";
// --
tw.Formatting = Formatting.Indented;
tw.WriteStartDocument();
tw.WriteStartElement(@"data");
((IXmlSerializable)table).WriteXml(tw);
tw.WriteEndElement();
tw.WriteEndDocument();
// --
tw.Flush();
tw.Close();
sw.Flush();
return sw.ToString();
}
}
}
Hopefully this is useful for someone somewhere out there.
(Please note that I asked in the past whether it is OK to post snippets and got replies that this should be OK; correct me if I am wrong on that - thanks!)
You can also try writing out the DataTable to XML which works just as nicely:
Dim dt As DataTable
Dim DataTableAsXMLString As String
'...code to populate DataTable
Using sw As New StringWriter()
dt.WriteXml(sw)
DataTableAsXMLString = sw.ToString()
End Using
...then if needed you can convert the XML right back to a DataTable:
Dim ds As New DataSet
Dim dt2 As DataTable
Using sr As New StringReader(DataTableAsXMLString)
ds.ReadXml(sr)
dt2 = ds.Tables(0)
End Using
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With