问题
I just found a few answers for this, but found them all horribly long with lots of iterations, so I came up with my own solution:
Convert table to string:
string myTableAsString = String.Join(Environment.NewLine, myDataTable.Rows.Cast<DataRow>(). Select(r => r.ItemArray).ToArray(). Select(x => String.Join("\t", x.Cast<string>())));
Then simply save string to text file, for example:
StreamWriter myFile = new StreamWriter("fileName.txt"); myFile.WriteLine(myFile); myFile.Close();
Is there a shorter / better way?
回答1:
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");
回答2:
@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.
回答3:
If you consider XML as text you can do: myDatatable.WriteXml("mydata.xml")
and myDatatable.ReadXml("mydata.xml")
回答4:
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.?
来源:https://stackoverflow.com/questions/30582668/shortest-way-to-save-datatable-to-textfile