Shortest way to save DataTable to Textfile

You have your DataTable named as myDataTable, you can add it to DataSet as:

var dataSet = new DataSet();
dataSet.AddTable(myDataTable);

// Write dataset to xml file or stream
dataSet.WriteXml("filename.xml");

And you can also read from xml file or stream:

dataSet.ReadXml("filename.xml");

You get an error unless you save it with the schema:

myDataTable.WriteXml("myXmlPath.xml", XmlWriteMode.WriteSchema);
myDatatable.ReadXml("myXmlPath.xml");

There is more info on saving/loading with schema here: DataTable does not support schema inference from Xml.?


If you consider XML as text you can do: myDatatable.WriteXml("mydata.xml") and myDatatable.ReadXml("mydata.xml")


@Leonardo sorry but i can 't comment so i post.

Sometimes you can ask the dataset and then work with it. Like this:

foreach (DataRow row in ds.Tables[0].Rows)
{
    foreach (object item in row.ItemArray)
    {
        myStreamWriter.Write((string)item + "\t");
    }
    myStreamWriter.WriteLine();
}

That 's another way but i don 't know which 'll give you a better metric.