Shortest way to save DataTable to Textfile

无人久伴 提交于 2020-04-10 08:23:06

问题


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:

  1. 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>())));
    
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!