Shortest way to save DataTable to Textfile

Leonardo Trivino picture Leonardo Trivino · Jun 1, 2015 · Viewed 24.2k times · Source

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?

Answer

rageit picture rageit · Jun 1, 2015

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");