Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest way to save DataTable to Textfile

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?

like image 337
Leonardo Trivino Avatar asked Jun 01 '15 20:06

Leonardo Trivino


1 Answers

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

like image 184
rlee Avatar answered Sep 20 '22 19:09

rlee