13

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?

Leonardo Trivino
  • 295
  • 1
  • 4
  • 11
  • 2
    How much shorter do you want it? – Rick S Jun 01 '15 at 20:29
  • 2
    Oneliner for saving to a file [`File.WriteAllText(location, content);`](https://msdn.microsoft.com/en-us/library/ms143375%28v=vs.110%29.aspx). There is also the predefined DataTable method [WriteXml(location)](https://msdn.microsoft.com/en-us/library/3hyx9hb4%28v=vs.110%29.aspx) that saves the content of the data table to a file. – keenthinker Jun 01 '15 at 20:30
  • 1
    If you have working code it does not belong on this site. This site is for fixing broken code. – deathismyfriend Jun 01 '15 at 20:31
  • If you can work with xml then you might be interested in adding the `DataTable` to `DataSet` and calling `WriteXml` on it. – rageit Jun 01 '15 at 20:35
  • I just was wondering if I am not just re-inventing the wheel. If there is a very simple and short way that I just couldn't find out there, I'd appreciate if someone can let me know. The important part is about converting the table into a string, but thanks for the tip to write to a file in a single line, I didn't know it. – Leonardo Trivino Jun 01 '15 at 20:36
  • It's easy to read, so I would imagine if it fits your needs and performance constraints, then there's no reason to over-engineer it. – Nate222 Jun 01 '15 at 20:40
  • @rageit Can you provide an example? – Leonardo Trivino Jun 01 '15 at 20:41
  • `var dataSet = new DataSet(); dataSet.Add(new DataTable()); dataSet.WriteXml("filename.xml");` – rageit Jun 01 '15 at 20:42

4 Answers4

15

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");
rageit
  • 3,513
  • 1
  • 26
  • 38
  • 2
    Why do you need to create the DataSet? Can't you just do `myDataTable.WriteXml("filename.xml")` as someone else suggested? – Leonardo Trivino Jun 01 '15 at 20:52
  • 3
    For some reason I was thinking about multiple tables. If you need just one table to be written then certainly you can go with `DataTable.WriteXml`. – rageit Jun 01 '15 at 20:56
  • 1
    FYI: In .NET Framework 4.6.2, there is no method on `System.Data.DataSet` named `AddTable` I used the `Add` method on `DataSet.Tables`. See [.NET Framework 4.6.2 Documentation for DataSet](https://learn.microsoft.com/en-us/dotnet/api/system.data.dataset?view=netframework-4.6.2) and [.NET Framework 4.6.2 Documentation for DataTableCollection.Add](https://learn.microsoft.com/en-us/dotnet/api/system.data.datatablecollection.add?view=netframework-4.6.2) – qxotk Sep 11 '19 at 15:39
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.

paulofer85
  • 555
  • 11
  • 15
2

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

rlee
  • 293
  • 1
  • 8
2

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.?

Danny
  • 896
  • 1
  • 9
  • 16