Aman
Aman

Reputation: 2276

Storing DataTable data in hard disk

Is it possible to store the data in a DataTable in the hard disk instead of the memory? By default, when a DataTable's being filled, the table (and data) will remain in memory. Would it be possible to save this data in another medium besides the memory? Everything would stay the same but instead of filling up the DataTable by storing it in the memory, I'd be storing it somewhere in the hard drive.

Upvotes: 3

Views: 4635

Answers (3)

Aman
Aman

Reputation: 2276

System.Data.DataTable implements ISerializable, so this is no big challenge: the following example uses binary serialization

using System.Runtime.Serialization.Formatters.Binary;

[...]

//Create DataTable and Serialize
private void button1_Click(object sender, System.EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("uid");
    dt.Columns.Add("test");
    
    for (int i = 0; i < 10; i++)
    {
        DataRow dr = dt.NewRow();
        dr[0] = i;
        dr[1] = string.Format("test{0}", i);
        dt.Rows.Add(dr);
    }

    FileStream fs = new FileStream(@"C:\test.bin", FileMode.Create);
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(fs, dt);
    fs.Close();
}

//Deserialize DataTable from File
private void button2_Click(object sender, System.EventArgs e)
{
    FileStream fs = new FileStream(@"C:\test.bin", FileMode.Open);
    BinaryFormatter bf = new BinaryFormatter();
    DataTable dt = (DataTable) bf.Deserialize(fs);
    fs.Close();
    
    foreach (DataRow dr in dt.Rows)
    {
        Debug.WriteLine(dr[0].ToString());
    }
}

Upvotes: 5

Steve
Steve

Reputation: 216313

The DataTable class has a method called WriteXml with many overloads that helps to write its content to disk

In its simplest form you could write this line

 myDataTable.WriteXml(somePathAndFileNameXML);

but, perhaps the better methods are the ones that allow to write also the schema data and the table data

  myDataTable.WriteXml.WriteXml(somePathAndFileNameXML, XmlWriteMode.WriteSchema);

The reverse is also possible with the ReadXml method

Upvotes: 4

TGH
TGH

Reputation: 39268

You can write it to disk and store it in a file or a database, but it has to be loaded in memory for your program to be able to interact with it.

Upvotes: 0

Related Questions