Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a DataTable to a string?

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?

like image 887
Uwe Keim Avatar asked Feb 11 '10 13:02

Uwe Keim


People also ask

How do you serialize a data set?

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.

Is DataTable serializable C#?

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.


2 Answers

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!)

like image 68
Uwe Keim Avatar answered Oct 26 '22 08:10

Uwe Keim


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
like image 30
atconway Avatar answered Oct 26 '22 08:10

atconway