Shortest way to save DataTable to Textfile

I just found some answers for this, but found them all terribly long with a lot 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 just save the line to a text file like:

    StreamWriter myFile = new StreamWriter("fileName.txt");
    myFile.WriteLine(myFile);
    myFile.Close();
    
          

Is there a shorter / better way?

+5


source to share


4 answers


You have one DataTable

called myDataTable, you can add it in DataSet

like:

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

      

+7


source


@Leonardo sorry but I cannot comment, so I post.

Sometimes you can query a 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();
}

      

This is another way, but I don't know which will give you the best metric.

+2


source


If you are considering XML as text you can do: myDatatable.WriteXml("mydata.xml")

andmyDatatable.ReadXml("mydata.xml")

+1


source


You will get an error if you don't save it with the schema:

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

      

There is more information about saving / loading with schema here: DataTable does not support schema output from XML.

0


source







All Articles